ALLIA12 commited on
Commit
af6f56c
·
verified ·
1 Parent(s): 48aaa95

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

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/372/Q3.ipynb +220 -0
  2. submissions_extracted/373/Q1.ipynb +346 -0
  3. submissions_extracted/373/Q2.ipynb +205 -0
  4. submissions_extracted/373/Q3.ipynb +370 -0
  5. submissions_extracted/374/Q1.ipynb +389 -0
  6. submissions_extracted/374/Q2.ipynb +448 -0
  7. submissions_extracted/374/Q3.ipynb +286 -0
  8. submissions_extracted/375/Q1.ipynb +315 -0
  9. submissions_extracted/375/Q2.ipynb +369 -0
  10. submissions_extracted/375/Q3.ipynb +265 -0
  11. submissions_extracted/376/Q1.ipynb +320 -0
  12. submissions_extracted/376/Q2.ipynb +408 -0
  13. submissions_extracted/376/Q3.ipynb +362 -0
  14. submissions_extracted/377/Q1.ipynb +421 -0
  15. submissions_extracted/377/Q2.ipynb +449 -0
  16. submissions_extracted/377/Q3.ipynb +162 -0
  17. submissions_extracted/378/Q1.ipynb +248 -0
  18. submissions_extracted/378/Q2.ipynb +314 -0
  19. submissions_extracted/378/Q3.ipynb +166 -0
  20. submissions_extracted/379/Q1.ipynb +281 -0
  21. submissions_extracted/379/Q2.ipynb +192 -0
  22. submissions_extracted/379/Q3.ipynb +160 -0
  23. submissions_extracted/38/Q1.ipynb +237 -0
  24. submissions_extracted/38/Q2.ipynb +192 -0
  25. submissions_extracted/38/Q3.ipynb +201 -0
  26. submissions_extracted/380/Q1.ipynb +205 -0
  27. submissions_extracted/380/Q2.ipynb +192 -0
  28. submissions_extracted/380/Q3.ipynb +183 -0
  29. submissions_extracted/381/Q1.ipynb +221 -0
  30. submissions_extracted/381/Q2.ipynb +423 -0
  31. submissions_extracted/381/Q3.ipynb +189 -0
  32. submissions_extracted/382/Q1.ipynb +227 -0
  33. submissions_extracted/382/Q2.ipynb +310 -0
  34. submissions_extracted/382/Q3.ipynb +251 -0
  35. submissions_extracted/383/Q1.ipynb +355 -0
  36. submissions_extracted/383/Q2.ipynb +366 -0
  37. submissions_extracted/383/Q3.ipynb +273 -0
  38. submissions_extracted/384/Q1.ipynb +459 -0
  39. submissions_extracted/384/Q2.ipynb +362 -0
  40. submissions_extracted/384/Q3.ipynb +329 -0
  41. submissions_extracted/385/Q1.ipynb +295 -0
  42. submissions_extracted/385/Q2.ipynb +340 -0
  43. submissions_extracted/385/Q3.ipynb +308 -0
  44. submissions_extracted/386/Q1.ipynb +335 -0
  45. submissions_extracted/386/Q2.ipynb +299 -0
  46. submissions_extracted/386/Q3.ipynb +303 -0
  47. submissions_extracted/387/Q1.ipynb +414 -0
  48. submissions_extracted/387/Q2.ipynb +426 -0
  49. submissions_extracted/387/Q3.ipynb +309 -0
  50. submissions_extracted/388/Q1.ipynb +499 -0
submissions_extracted/372/Q3.ipynb ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
30
+ "\n",
31
+ "df = pd.read_csv(csv_path)"
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)"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# Task 2: Write your code here:\n",
90
+ "def check_duplicates(df):\n",
91
+ " duplicates = df.duplicated().sum()\n",
92
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
93
+ " if duplicates > 0:\n",
94
+ " print(\"Dropping Duplicates...\")\n",
95
+ " df.drop_duplicates(inplace=True)\n",
96
+ " print(\"Duplicates Dropped.\")\n",
97
+ " else:\n",
98
+ " print(\"No Duplicate Samples Found.\")\n",
99
+ "\n",
100
+ "check_duplicates(df)"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 3: Write your code here:"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 4: Write your code here:\n",
119
+ "from sklearn.preprocessing import StandardScaler\n",
120
+ "\n",
121
+ "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
122
+ "\n",
123
+ "scaler = StandardScaler()\n",
124
+ "df[features] = scaler.fit_transform(df[features])\n",
125
+ "df.head()"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# Task 5: Write your code here:"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# Task 1: Write your code here:\n",
144
+ "X = df.drop(\"target\", axis=1).astype(float)\n",
145
+ "y = df[\"target\"].astype(float)"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# Task 2,3,4,5: Write your code here:\n",
155
+ "from sklearn.model_selection import StratifiedKFold, train_test_split\n",
156
+ "from sklearn.metrics import accuracy_score\n",
157
+ "from catboost import CatBoostClassifier\n",
158
+ "\n",
159
+ "model=CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n",
160
+ "n_splits = 5\n",
161
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
162
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
163
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
164
+ "#\n",
165
+ " # Get the train & test split for this fold\n",
166
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
167
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
168
+ " # Fit the model on train data\n",
169
+ " model.fit(X_train, y_train)\n",
170
+ "\n",
171
+ "# Use the model to predict the test data\n",
172
+ " y_pred = model.predict(X_test)\n",
173
+ "\n",
174
+ "# Calculate evaluation metrics\n",
175
+ " accuracy = accuracy_score(y_test, y_pred)\n",
176
+ "print(f\"Accuracy: {accuracy}\")"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 1: Write your code here:"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 2: Write your code here:"
195
+ ],
196
+ "execution_count": null,
197
+ "outputs": []
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "metadata": {},
202
+ "source": [
203
+ "# Task Bonus: Write your code here:"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ }
208
+ ],
209
+ "metadata": {
210
+ "kernelspec": {
211
+ "display_name": "Python 3",
212
+ "name": "python3"
213
+ },
214
+ "language_info": {
215
+ "name": "python"
216
+ }
217
+ },
218
+ "nbformat": 4,
219
+ "nbformat_minor": 0
220
+ }
submissions_extracted/373/Q1.ipynb ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import seaborn as sns\n",
13
+ "from tqdm import tqdm\n",
14
+ "\n",
15
+ "from sklearn.model_selection import train_test_split, KFold\n",
16
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
17
+ "from sklearn.ensemble import RandomForestRegressor\n",
18
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
19
+ "from sklearn.preprocessing import OneHotEncoder\n",
20
+ "import warnings\n",
21
+ "warnings.filterwarnings('ignore')"
22
+ ],
23
+ "execution_count": null,
24
+ "outputs": []
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "metadata": {},
29
+ "source": [
30
+ "import kagglehub\n",
31
+ "\n",
32
+ "# Download latest version\n",
33
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
34
+ "\n",
35
+ "print(\"Path to dataset files:\", path)"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task1 read data:\n",
45
+ "# Load the dataset\n",
46
+ "delivery_path = os.path.join(path,'Q1_data.csv')\n",
47
+ "df_delivery = pd.read_csv(delivery_path)\n",
48
+ "\n",
49
+ "print(f\"Dataset shape: {df_delivery.shape}\")"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 2: using head to show first rows data:\n",
59
+ "df_delivery.head()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 3: display info to show information of data:\n",
69
+ "df_delivery.info()"
70
+ ],
71
+ "execution_count": null,
72
+ "outputs": []
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "metadata": {},
77
+ "source": [
78
+ "# Task 4: using describe to know the details of data\n",
79
+ "df_delivery.describe()"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# Task 5:\n",
89
+ "# delivery_time distribution (target variable)\n",
90
+ "plt.figure(figsize=(10, 5))\n",
91
+ "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
92
+ "plt.title('delivery_time Distribution')\n",
93
+ "plt.xlabel('delivery_time')\n",
94
+ "plt.ylabel('Frequency')\n",
95
+ "plt.show()"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# Task 1: drop ID column\n",
105
+ "print(f\"Before: {df_delivery.shape}\")\n",
106
+ "df_delivery = df_delivery.drop(columns=['Order_ID'])\n",
107
+ "print(f\"After dropping Order_ID column: {df_delivery.shape}\")\n",
108
+ "\n",
109
+ "df_delivery"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 2: check the missing\n",
119
+ "def check_missing_values(df_delivery):\n",
120
+ " missing_values = df_delivery.isnull().sum()\n",
121
+ " print(\"Missing Values per Column:\")\n",
122
+ " print(missing_values[missing_values > 0])\n",
123
+ " if missing_values.any():\n",
124
+ " print(\"\\nHandle Missing Values as needed.\")\n",
125
+ " else:\n",
126
+ " print(\"\\nNo Missing Values Found.\")\n",
127
+ "\n",
128
+ "check_missing_values(df_delivery)\n",
129
+ "\n",
130
+ "at_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n",
131
+ "# Drop rows with missing stat values\n",
132
+ "df_delivery = df_delivery.dropna(subset=at_cols).copy()\n",
133
+ "print(f\"Shape after cleaning: {df_delivery.shape}\")\n"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 3: Dublicate\n",
143
+ "def check_duplicates(df_delivery):\n",
144
+ " duplicates = df_delivery.duplicated().sum()\n",
145
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
146
+ " if duplicates > 0:\n",
147
+ " print(\"Dropping Duplicates...\")\n",
148
+ " df_delivery.drop_duplicates(inplace=True)\n",
149
+ " print(\"Duplicates Dropped.\")\n",
150
+ " else:\n",
151
+ " print(\"No Duplicate Samples Found.\")\n",
152
+ "\n",
153
+ "check_duplicates(df_delivery)"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 4: Do we have categorical columns?\n",
163
+ "# encoding\n",
164
+ "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns\n",
165
+ "for col in categorical_cols:\n",
166
+ " print(f\"Encoding column: {col}\")\n",
167
+ " le = LabelEncoder()\n",
168
+ " df_delivery[col] = le.fit_transform(df_delivery[col])\n",
169
+ "df_delivery\n"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 5:\n",
186
+ "numerical_cols = df_delivery.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
187
+ "\n",
188
+ "scaler = StandardScaler()\n",
189
+ "df_delivery[numerical_cols] = scaler.fit_transform(df_delivery[numerical_cols])\n",
190
+ "df_delivery.head()\n"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "# Task 6:\n",
200
+ "def check_target_imbalance(df_delivery, target_column):\n",
201
+ " print(\"Target Distribution:\")\n",
202
+ " print(df_delivery[target_column].value_counts(normalize=True))\n",
203
+ " sns.countplot(x=df_delivery[target_column])\n",
204
+ " plt.title(\"Target Distribution\")\n",
205
+ " plt.show()\n",
206
+ "\n",
207
+ "check_target_imbalance(df_delivery, \"Delivery_Time\")"
208
+ ],
209
+ "execution_count": null,
210
+ "outputs": []
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "metadata": {},
215
+ "source": [
216
+ "# Task 1:\n",
217
+ "feature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
218
+ "X = df_delivery[feature_cols]\n",
219
+ "y = df_delivery['Delivery_Time']\n",
220
+ "\n",
221
+ "# Train-test split (80% train, 20% test)\n",
222
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
223
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
224
+ ],
225
+ "execution_count": null,
226
+ "outputs": []
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "metadata": {},
231
+ "source": [
232
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
233
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
234
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
235
+ " losses = []\n",
236
+ "\n",
237
+ " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
238
+ " y_hat = np.dot(X, theta)\n",
239
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
240
+ " theta -= learning_rate * gradient\n",
241
+ "\n",
242
+ " loss = mean_squared_error(y, y_hat)\n",
243
+ " losses.append(loss)\n",
244
+ "\n",
245
+ " return theta, losses"
246
+ ],
247
+ "execution_count": null,
248
+ "outputs": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "metadata": {},
253
+ "source": [
254
+ "lr_losses = []\n",
255
+ "lr_mse = []\n",
256
+ "lr_rmse = []\n",
257
+ "lr_r2 = []"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Task 2,3,4,5: Write your code here:\n",
267
+ "#task3\n",
268
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
269
+ "model.fit(X_train, y_train)\n",
270
+ "print(\"Model trained!\")\n",
271
+ "\n",
272
+ "#MSE\n",
273
+ "y_pred = model.predict(X_test)\n",
274
+ "mae = mean_absolute_error(y_test, y_pred)\n",
275
+ "print(f\"MAE: ${mae:,.2f}\")\n",
276
+ "\n",
277
+ "#\n",
278
+ "# K-Fold Cross Validation\n",
279
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
280
+ "\n",
281
+ "\n",
282
+ "\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\n",
294
+ "feature_importance = pd.DataFrame({\n",
295
+ " 'feature': feature_cols,\n",
296
+ " 'importance': model.feature_importances_\n",
297
+ "}).sort_values('importance', ascending=False)\n",
298
+ "\n",
299
+ "plt.figure(figsize=(10, 6))\n",
300
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
301
+ "plt.xlabel('Importance')\n",
302
+ "plt.title('Feature Importance')\n",
303
+ "plt.gca().invert_yaxis()\n",
304
+ "plt.show()"
305
+ ],
306
+ "execution_count": null,
307
+ "outputs": []
308
+ },
309
+ {
310
+ "cell_type": "code",
311
+ "metadata": {},
312
+ "source": [
313
+ "# Task 2: Write your code here:\n",
314
+ "plt.xlabel(\"Actual Dilvery time (Ground Truth)\")\n",
315
+ "plt.ylabel(\"Predicted Dilvery time\")\n",
316
+ "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n",
317
+ "plt.grid(True)\n",
318
+ "\n",
319
+ "plt.tight_layout()\n",
320
+ "plt.show()"
321
+ ],
322
+ "execution_count": null,
323
+ "outputs": []
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "metadata": {},
328
+ "source": [
329
+ "# Task Bonus: Write your code here:"
330
+ ],
331
+ "execution_count": null,
332
+ "outputs": []
333
+ }
334
+ ],
335
+ "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/373/Q2.ipynb ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import torch\n",
10
+ "import torch.nn as nn\n",
11
+ "from torch.optim import AdamW\n",
12
+ "from torchvision.transforms.functional import to_tensor\n",
13
+ "from torch.utils.data import DataLoader\n",
14
+ "\n",
15
+ "# Download latest version\n",
16
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
17
+ "\n",
18
+ "print(\"Path to dataset files:\", path)"
19
+ ],
20
+ "execution_count": null,
21
+ "outputs": []
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "import os\n",
28
+ "import pandas as pd\n",
29
+ "import numpy as np\n",
30
+ "from PIL import Image\n",
31
+ "from sklearn.model_selection import train_test_split\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
+ "# Training dataset\n",
76
+ "train_dataset = images(root='./datasets', train=True, transform=to_tensor, download=True)\n",
77
+ "# Testing dataset\n",
78
+ "test_dataset = images(root='./datasets', train=False, transform=to_tensor, download=True)\n",
79
+ "\n",
80
+ "# Print one sample from the dataset\n",
81
+ "sample_image, sample_label = train_dataset[0]\n",
82
+ "print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n",
83
+ "print(f\"Label: {sample_label}\")\n"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# 2. Create TensorDataset objects\n",
93
+ "\n",
94
+ "\n"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# 3. Create DataLoaders\n",
104
+ "\n",
105
+ "\n"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# 4. Print shape of one batch\n",
115
+ "\n"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# 5. Display sample images\n",
125
+ "\n"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# Task 1: Write your model class here:"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# Task 2: Write your training loop here:"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "# Task 3: Write your validation loop here:"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 4: Define device, model, loss, optimizer:"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 5: Start training for 20 epochs:"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 1: Write your code here:"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 2 (Bonus): Write your code here:"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ }
193
+ ],
194
+ "metadata": {
195
+ "kernelspec": {
196
+ "display_name": "Python 3",
197
+ "name": "python3"
198
+ },
199
+ "language_info": {
200
+ "name": "python"
201
+ }
202
+ },
203
+ "nbformat": 4,
204
+ "nbformat_minor": 0
205
+ }
submissions_extracted/373/Q3.ipynb ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import seaborn as sns\n",
14
+ "from tqdm import tqdm\n",
15
+ "\n",
16
+ "from sklearn.model_selection import train_test_split, KFold\n",
17
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
18
+ "from sklearn.ensemble import RandomForestRegressor\n",
19
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
20
+ "from sklearn.preprocessing import OneHotEncoder\n",
21
+ "import warnings\n",
22
+ "\n",
23
+ "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n",
24
+ "warnings.filterwarnings('ignore')\n",
25
+ "\n",
26
+ "# Download latest version\n",
27
+ "\n",
28
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-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
+ "# Task 1: Write your code here:\n",
40
+ "df_path = os.path.join(path,'Q3_data.csv')\n",
41
+ "df = pd.read_csv(df_path)\n",
42
+ "\n",
43
+ "print(f\"Dataset shape: {df.shape}\")"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Task 2: Write your code here:\n",
53
+ "df.head()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 3: Write your code here:\n",
63
+ "df.info()"
64
+ ],
65
+ "execution_count": null,
66
+ "outputs": []
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "metadata": {},
71
+ "source": [
72
+ "# Task 4: Write your code here:\n",
73
+ "df.describe()"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# Task 1: Write your code here:\n",
83
+ "def check_missing_values(df):\n",
84
+ " missing_values = df.isnull().sum()\n",
85
+ " print(\"Missing Values per Column:\")\n",
86
+ " print(missing_values[missing_values > 0])\n",
87
+ " if missing_values.any():\n",
88
+ " print(\"\\nHandle Missing Values as needed.\")\n",
89
+ " else:\n",
90
+ " print(\"\\nNo Missing Values Found.\")\n",
91
+ "\n",
92
+ "check_missing_values(df)\n",
93
+ "\n",
94
+ "at_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','D_137',\t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145',\t'Target']\n",
95
+ "\n",
96
+ "df[at_cols] = df[at_cols].fillna('none')\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 2: Write your code here:\n",
106
+ "def check_duplicates(df):\n",
107
+ " duplicates = df.duplicated().sum()\n",
108
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
109
+ " if duplicates > 0:\n",
110
+ " print(\"Dropping Duplicates...\")\n",
111
+ " df.drop_duplicates(inplace=True)\n",
112
+ " print(\"Duplicates Dropped.\")\n",
113
+ " else:\n",
114
+ " print(\"No Duplicate Samples Found.\")\n",
115
+ "\n",
116
+ "check_duplicates(df)"
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
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
127
+ "\n",
128
+ "print(\"Categorical Columns:\", list(categorical_cols))\n"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 4: Write your code here:\n",
138
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
139
+ "\n",
140
+ "scaler = StandardScaler()\n",
141
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
142
+ "df.head()"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 5: Write your code here:\n",
152
+ "def check_target_imbalance(df, target_column):\n",
153
+ " print(\"Target Distribution:\")\n",
154
+ " print(df[target_column].value_counts(normalize=True))\n",
155
+ " sns.countplot(x=df[target_column])\n",
156
+ " plt.title(\"Target Distribution\")\n",
157
+ " plt.show()\n",
158
+ "\n",
159
+ "check_target_imbalance(df, \"Target\")"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your code here:\n",
169
+ "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','D_137',\t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145']\n",
170
+ "X = df[feature_cols]\n",
171
+ "y = df['Target']\n",
172
+ "\n",
173
+ "# Train-test split (80% train, 20% test)\n",
174
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
175
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "from sklearn.model_selection import StratifiedKFold\n",
185
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
195
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
196
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
197
+ " losses = []\n",
198
+ "\n",
199
+ " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
200
+ " y_hat = np.dot(X, theta)\n",
201
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
202
+ " theta -= learning_rate * gradient\n",
203
+ "\n",
204
+ " loss = mean_squared_error(y, y_hat)\n",
205
+ " losses.append(loss)\n",
206
+ "\n",
207
+ " return theta, losses"
208
+ ],
209
+ "execution_count": null,
210
+ "outputs": []
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "metadata": {},
215
+ "source": [
216
+ "from sklearn.linear_model import LogisticRegression\n",
217
+ "from sklearn.neighbors import KNeighborsClassifier\n",
218
+ "from sklearn.svm import SVC\n",
219
+ "from sklearn.tree import DecisionTreeClassifier\n",
220
+ "from sklearn.ensemble import RandomForestClassifier\n",
221
+ "from xgboost import XGBClassifier\n",
222
+ "from catboost import CatBoostClassifier"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "models = {\n",
232
+ " \"LR\": LogisticRegression(\n",
233
+ " max_iter=1000\n",
234
+ " ),\n",
235
+ " \"KNN\": KNeighborsClassifier(\n",
236
+ " n_neighbors=3,\n",
237
+ " ),\n",
238
+ " \"SVM\": SVC(\n",
239
+ " kernel='rbf',\n",
240
+ " C=1.0\n",
241
+ " ),\n",
242
+ " \"Decision Tree\": DecisionTreeClassifier(\n",
243
+ " max_depth=16\n",
244
+ " ),\n",
245
+ " \"Random Forest\": RandomForestClassifier(\n",
246
+ " n_estimators=200,\n",
247
+ " max_depth=10\n",
248
+ " ),\n",
249
+ " \"XGBoost\": XGBClassifier(\n",
250
+ " verbosity=0,\n",
251
+ " n_estimators=280,\n",
252
+ " max_depth=10,\n",
253
+ " ),\n",
254
+ " \"CatBoost\": CatBoostClassifier(\n",
255
+ " verbose=0,\n",
256
+ " n_estimators=200,\n",
257
+ " max_depth=4\n",
258
+ " )\n",
259
+ "}"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Task 2,3,4,5: Write your code here:\n",
269
+ "n_splits = 5 # K=5 Folds\n",
270
+ "\n",
271
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
272
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
273
+ "\n",
274
+ "lr_losses = []\n",
275
+ "lr_accuracy = []\n",
276
+ "lr_precision = []\n",
277
+ "lr_recall = []\n",
278
+ "lr_f1 = []\n",
279
+ "\n",
280
+ "model = CatBoostClassifier(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
281
+ "model.fit(X_train, y_train)\n",
282
+ "print(\"Model trained!\")\n",
283
+ "\n",
284
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
285
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
286
+ "\n",
287
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
288
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
289
+ "\n",
290
+ " # Train\n",
291
+ " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
292
+ "\n",
293
+ " # Validate\n",
294
+ " y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
295
+ " y_pred = (y_pred_proba >= 0.5).astype(int)\n",
296
+ "\n",
297
+ " # Calculate evaluation metrics\n",
298
+ " accuracy = accuracy_score(y_test, y_pred)\n",
299
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
300
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
301
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
302
+ "\n",
303
+ " # Store results\n",
304
+ " lr_losses.append(losses)\n",
305
+ " lr_accuracy.append(accuracy)\n",
306
+ " lr_precision.append(precision)\n",
307
+ " lr_recall.append(recall)\n",
308
+ " lr_f1.append(f1)"
309
+ ],
310
+ "execution_count": null,
311
+ "outputs": []
312
+ },
313
+ {
314
+ "cell_type": "code",
315
+ "metadata": {},
316
+ "source": [
317
+ "# Task 1: Write your code here:\n",
318
+ "feature_importance = pd.DataFrame({\n",
319
+ " 'feature': feature_cols,\n",
320
+ " 'importance': model.feature_importances_\n",
321
+ "}).sort_values('importance', ascending=False)\n",
322
+ "\n",
323
+ "plt.figure(figsize=(10, 6))\n",
324
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
325
+ "plt.xlabel('Importance')\n",
326
+ "plt.title('Feature Importance')\n",
327
+ "plt.gca().invert_yaxis()\n",
328
+ "plt.show()"
329
+ ],
330
+ "execution_count": null,
331
+ "outputs": []
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "metadata": {},
336
+ "source": [
337
+ "# Task 2: Write your code here:\n",
338
+ "plt.xlabel(\"Actual golden feature (Ground Truth)\")\n",
339
+ "plt.ylabel(\"Predicted golden feature\")\n",
340
+ "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n",
341
+ "plt.grid(True)\n",
342
+ "\n",
343
+ "plt.tight_layout()\n",
344
+ "plt.show()"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "source": [
353
+ "# Task Bonus: Write your code here:"
354
+ ],
355
+ "execution_count": null,
356
+ "outputs": []
357
+ }
358
+ ],
359
+ "metadata": {
360
+ "kernelspec": {
361
+ "display_name": "Python 3",
362
+ "name": "python3"
363
+ },
364
+ "language_info": {
365
+ "name": "python"
366
+ }
367
+ },
368
+ "nbformat": 4,
369
+ "nbformat_minor": 0
370
+ }
submissions_extracted/374/Q1.ipynb ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import pandas as pd\n",
22
+ "import numpy as np\n",
23
+ "import matplotlib.pyplot as plt\n",
24
+ "import seaborn as sns\n",
25
+ "import os"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "# Task 1: Write your code here:\n",
35
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
36
+ "\n",
37
+ "df = pd.read_csv(csv_path)"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "df.head()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 3: Write your code here:\n",
57
+ "df.info()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 4: Write your code here:\n",
67
+ "df.describe()"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# Task 5: Write your code here:\n",
77
+ "plt.figure(figsize=(10, 5))\n",
78
+ "plt.hist(df['Delivery_Time'].dropna(), bins=20, edgecolor='black')\n",
79
+ "plt.title('distribution of Delivery_Time')\n",
80
+ "plt.xlabel('Delivery_Time')\n",
81
+ "plt.ylabel('Frequency')\n",
82
+ "plt.show()"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# Task 1: Write your code here:\n",
92
+ "df = df.drop(['Order_ID'], axis=1)\n",
93
+ "df.head()"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 2: Write your code here:\n",
103
+ "def check_missing_values(df):\n",
104
+ " missing_values = df.isnull().sum()\n",
105
+ " print(\"Missing Values per Column:\")\n",
106
+ " print(missing_values[missing_values > 0])\n",
107
+ " if missing_values.any():\n",
108
+ " print(\"\\nHandle Missing Values as needed.\")\n",
109
+ " else:\n",
110
+ " print(\"\\nNo Missing Values Found.\")\n",
111
+ "\n",
112
+ "check_missing_values(df)"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "categorical_column = df.select_dtypes(include='object').columns\n",
122
+ "for col in categorical_column:\n",
123
+ " df[col] = df[col].fillna('Unknown')"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "check_missing_values(df)"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "df[\"Courier_Experience_yrs\"] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "df[\"Delivery_Time\"] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "check_missing_values(df)"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 3: Write your code here:\n",
169
+ "def check_duplicates(df):\n",
170
+ " duplicates = df.duplicated().sum()\n",
171
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
172
+ " if duplicates > 0:\n",
173
+ " print(\"Dropping Duplicates...\")\n",
174
+ " df.drop_duplicates(inplace=True)\n",
175
+ " print(\"Duplicates Dropped.\")\n",
176
+ " else:\n",
177
+ " print(\"No Duplicate Samples Found.\")\n",
178
+ "\n",
179
+ "check_duplicates(df)"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# check again\n",
189
+ "check_duplicates(df)"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 4: Write your code here:\n",
199
+ "from sklearn.preprocessing import OneHotEncoder\n",
200
+ "\n",
201
+ "categorical_cols = df.select_dtypes(include=['object']).columns\n",
202
+ "\n",
203
+ "for col in categorical_cols:\n",
204
+ " print(f\"Encoding column: {col}\")\n",
205
+ " ohe = OneHotEncoder(sparse_output=False)\n",
206
+ "\n",
207
+ " df = df.join(\n",
208
+ " pd.DataFrame(\n",
209
+ " ohe.fit_transform(df[[col]]),\n",
210
+ " columns=ohe.get_feature_names_out([col]),\n",
211
+ " index=df.index\n",
212
+ " )\n",
213
+ " ).drop(columns=[col])\n",
214
+ "\n",
215
+ "df.head()\n"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "# Task 5: Write your code here:\n",
225
+ "from sklearn.preprocessing import StandardScaler\n",
226
+ "\n",
227
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n",
228
+ "\n",
229
+ "scaler = StandardScaler()\n",
230
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
231
+ "df.head()"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task 6: Write your code here:\n",
241
+ "df[\"Delivery_Time\"].value_counts()"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "## The target is imbalanced"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": []
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "metadata": {},
258
+ "source": [
259
+ "# Task 1: Write your code here:\n",
260
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
261
+ "y = df['Delivery_Time'].astype(float)"
262
+ ],
263
+ "execution_count": null,
264
+ "outputs": []
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "metadata": {},
269
+ "source": [
270
+ "feature_cols = [\"Distance_km\", \"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\", \"Preparation_Time_min\",\n",
271
+ " \"Courier_Experience_yrs\", \"Delivery_Time\"\n",
272
+ " ]"
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "metadata": {},
280
+ "source": [
281
+ "# Task 2,3,4,5: Write your code here:\n",
282
+ "\n",
283
+ "# we will use StratifiedKFold because the imbalance\n",
284
+ "from sklearn.model_selection import StratifiedKFold\n",
285
+ "from sklearn.ensemble import RandomForestRegressor\n"
286
+ ],
287
+ "execution_count": null,
288
+ "outputs": []
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "metadata": {},
293
+ "source": [
294
+ "from sklearn.metrics import mean_absolute_error as sklearn_mae\n",
295
+ "\n",
296
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
297
+ "\n",
298
+ "mae_scores = []\n",
299
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
300
+ "\n",
301
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
302
+ " # indexing for each fold\n",
303
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
304
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
305
+ "\n",
306
+ " print(f\"Fold {fold}\")\n",
307
+ " print(\" X_train shape:\", X_train.shape)\n",
308
+ " print(\" X_test shape :\", X_test.shape)\n",
309
+ " print(\" y_train shape:\", y_train.shape)\n",
310
+ " print(\" y_test shape :\", y_test.shape)\n",
311
+ "\n",
312
+ "\n",
313
+ " model = RandomForestRegressor(n_estimators=200)\n",
314
+ "\n",
315
+ " model.fit(X_train, y_train)\n",
316
+ "\n",
317
+ " y_pred = model.predict(X_test)\n",
318
+ "\n",
319
+ " mae_scores.append(sklearn_mae(y_test, y_pred))\n",
320
+ "\n",
321
+ "mae_scores = np.array(mae_scores)\n",
322
+ "\n",
323
+ "print(f\"5-Fold Results:\")\n",
324
+ "print(f\"MAE: {mae_scores.mean():,.2f}\")"
325
+ ],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "metadata": {},
332
+ "source": [
333
+ "# Task 1: Write your code here:\n",
334
+ "feature_importance = pd.DataFrame({\n",
335
+ " 'feature': X.columns,\n",
336
+ " 'importance': model.feature_importances_\n",
337
+ "}).sort_values('importance', ascending=False)\n",
338
+ "\n",
339
+ "plt.figure(figsize=(10, 6))\n",
340
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
341
+ "plt.xlabel('Importance')\n",
342
+ "plt.title('Feature Importance')\n",
343
+ "plt.gca().invert_yaxis()\n",
344
+ "plt.show()"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "source": [
353
+ "# Task 2: Write your code here:\n",
354
+ "plt.figure(figsize=(6, 4))\n",
355
+ "plt.scatter(y_test, y_pred, alpha=0.7)\n",
356
+ "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n",
357
+ "plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
358
+ "plt.ylabel(\"Predicted y_pred \")\n",
359
+ "plt.title(\"Predictions vs. Ground Truth\")\n",
360
+ "plt.grid(True)\n",
361
+ "\n",
362
+ "plt.tight_layout()\n",
363
+ "plt.show()"
364
+ ],
365
+ "execution_count": null,
366
+ "outputs": []
367
+ },
368
+ {
369
+ "cell_type": "code",
370
+ "metadata": {},
371
+ "source": [
372
+ "# Task Bonus: Write your code here:"
373
+ ],
374
+ "execution_count": null,
375
+ "outputs": []
376
+ }
377
+ ],
378
+ "metadata": {
379
+ "kernelspec": {
380
+ "display_name": "Python 3",
381
+ "name": "python3"
382
+ },
383
+ "language_info": {
384
+ "name": "python"
385
+ }
386
+ },
387
+ "nbformat": 4,
388
+ "nbformat_minor": 0
389
+ }
submissions_extracted/374/Q2.ipynb ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "import torch.nn as nn\n",
71
+ "\n",
72
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
73
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
74
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
75
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\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
+ "from torch.utils.data import TensorDataset\n",
86
+ "from torch.utils.data import DataLoader\n",
87
+ "\n",
88
+ "train_dataset = TensorDataset(X_train, y_train)\n",
89
+ "test_dataset = TensorDataset(X_test, y_test)\n",
90
+ "\n"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# 3. Create DataLoaders\n",
100
+ "from torch.utils.data import DataLoader\n",
101
+ "\n",
102
+ "# DataLoader for training data\n",
103
+ "train_loader = DataLoader(\n",
104
+ " train_dataset,\n",
105
+ " batch_size=32,\n",
106
+ " shuffle=True,\n",
107
+ " num_workers=2\n",
108
+ ")\n",
109
+ "# DataLoader for test/validation data\n",
110
+ "test_loader = DataLoader(\n",
111
+ " test_dataset,\n",
112
+ " batch_size=32,\n",
113
+ " shuffle=False,\n",
114
+ " num_workers=2\n",
115
+ ")\n",
116
+ "\n",
117
+ "\n"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# 4. Print shape of one batch\n",
127
+ "\n",
128
+ "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
+ "\n",
141
+ "sample_image, sample_label = train_dataset[0]\n",
142
+ "print(f\"Image shape: {sample_image.shape}\")\n",
143
+ "print(f\"Label: {sample_label}\")\n"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "import matplotlib.pyplot as plt\n",
153
+ "images, labels = next(iter(train_loader))\n",
154
+ "\n",
155
+ "# Display the first 5 images in the batch\n",
156
+ "plt.figure(figsize=(8, 4))\n",
157
+ "\n",
158
+ "for i in range(5):\n",
159
+ " plt.subplot(2, 3, i + 1)\n",
160
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
161
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
162
+ " plt.axis('off')\n",
163
+ "\n",
164
+ "plt.tight_layout()\n",
165
+ "plt.show()"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 1: Write your model class here:\n",
175
+ "class NN3Layer(nn.Module):\n",
176
+ "\n",
177
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
178
+ " super(NN3Layer, self).__init__()\n",
179
+ "\n",
180
+ " # First linear layer: input features -> hidden layer\n",
181
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
182
+ "\n",
183
+ " # Second linear layer: hidden layer -> hidden layer\n",
184
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
185
+ "\n",
186
+ " # 3id linear layer: hidden layer -> hidden layer\n",
187
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
188
+ "\n",
189
+ " # Output layer: hidden layer -> number of classes (logits)\n",
190
+ " self.layer3 = nn.Linear(hidden_dim, output_dim)\n",
191
+ "\n",
192
+ " # ReLU activation for non-linearity\n",
193
+ " self.relu = nn.ReLU()\n",
194
+ "\n",
195
+ " # Defines how input data flows through the network\n",
196
+ " def forward(self, x):\n",
197
+ " # First hidden layer\n",
198
+ " z1 = self.layer1(x)\n",
199
+ " a1 = self.relu(z1)\n",
200
+ "\n",
201
+ " # Second hidden layer\n",
202
+ " z2 = self.layer2(a1)\n",
203
+ " a2 = self.relu(z2)\n",
204
+ "\n",
205
+ " # 3id hidden layer\n",
206
+ " z3 = self.layer2(a2)\n",
207
+ " a3 = self.relu(z3)\n",
208
+ "\n",
209
+ " # Output layer\n",
210
+ " z4 = self.layer3(a3)\n",
211
+ "\n",
212
+ " return z4"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "# Task 2: Write your training loop here:\n",
222
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
223
+ " # Set the model to training mode\n",
224
+ " model.train()\n",
225
+ "\n",
226
+ " running_loss = 0.0\n",
227
+ "\n",
228
+ " for X_batch, y_batch in train_loader:\n",
229
+ "\n",
230
+ " # Reshape square images into flattened vectors\n",
231
+ " # (Note: Without changing the batch dimension!)\n",
232
+ " X_batch = X_batch.view(X_batch.size(0), -1)\n",
233
+ "\n",
234
+ "\n",
235
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
236
+ "\n",
237
+ "\n",
238
+ " # Move batch to the selected device\n",
239
+ " X_batch = X_batch.to(device)\n",
240
+ " y_batch = y_batch.to(device)\n",
241
+ "\n",
242
+ " # Forward pass\n",
243
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
244
+ " outputs = torch.tensor(outputs, dtype=torch.long)\n",
245
+ " loss = criterion(outputs, y_batch)\n",
246
+ "\n",
247
+ " # Backward pass & optimization\n",
248
+ " optimizer.zero_grad() # Clear previous gradients\n",
249
+ " loss.backward() # Compute gradients\n",
250
+ " optimizer.step() # Update model parameters\n",
251
+ "\n",
252
+ " running_loss += loss.item()\n",
253
+ "\n",
254
+ " # Average loss over all batches\n",
255
+ " avg_loss = running_loss / len(train_loader)\n",
256
+ "\n",
257
+ " return avg_loss"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Task 3: Write your validation loop here:\n",
267
+ "import torch.nn.functional as F\n",
268
+ "\n",
269
+ "def validate(model, criterion, test_loader, device):\n",
270
+ " # Set the model to evaluation mode\n",
271
+ " model.eval()\n",
272
+ "\n",
273
+ " running_loss = 0.0\n",
274
+ " correct = 0\n",
275
+ " total = 0\n",
276
+ "\n",
277
+ " with torch.no_grad():\n",
278
+ " for X_batch, y_batch in test_loader:\n",
279
+ "\n",
280
+ " # Reshape square images into flattened vectors\n",
281
+ " # (Note: Without changing the batch dimension!)\n",
282
+ " X_batch = X_batch.view(X_batch.size(0), -1)\n",
283
+ "\n",
284
+ " # Move batch to the selected device\n",
285
+ " X_batch = X_batch.to(device)\n",
286
+ " y_batch = y_batch.to(device)\n",
287
+ "\n",
288
+ "\n",
289
+ " # Forward pass\n",
290
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
291
+ " loss = criterion(outputs, y_batch)\n",
292
+ " running_loss += loss.item()\n",
293
+ "\n",
294
+ " # Apply Softmax to get probabilities\n",
295
+ " probabilities = F.softmax(outputs, dim=1)\n",
296
+ "\n",
297
+ " # Multiclass predictions\n",
298
+ " predicted = torch.argmax(probabilities, dim=1)\n",
299
+ "\n",
300
+ " # Accuracy calculation\n",
301
+ " correct += (predicted == y_batch).sum().item()\n",
302
+ " total += y_batch.size(0)\n",
303
+ "\n",
304
+ " avg_loss = running_loss / len(test_loader)\n",
305
+ " accuracy = correct / total\n",
306
+ "\n",
307
+ " return avg_loss, accuracy"
308
+ ],
309
+ "execution_count": null,
310
+ "outputs": []
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "metadata": {},
315
+ "source": [
316
+ "# Task 4: Define device, model, loss, optimizer:\n",
317
+ "from torch.optim import Adam\n",
318
+ "\n",
319
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
320
+ "\n",
321
+ "# Model parameters\n",
322
+ "input_dim = 36 * 36 *3\n",
323
+ "hidden_dim = 10\n",
324
+ "output_dim = 1 # the probability of the face age\n",
325
+ "\n",
326
+ "# Instantiate model\n",
327
+ "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
328
+ "\n",
329
+ "# Print the model architecture\n",
330
+ "print(\"Model Architecture:\\n\")\n",
331
+ "print(model)\n",
332
+ "\n",
333
+ "# Calculate the total number of trainable parameters\n",
334
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
335
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
336
+ "\n",
337
+ "\n",
338
+ "num_epochs = 20\n",
339
+ "learning_rate = 0.001\n",
340
+ "\n",
341
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
342
+ "criterion = nn.CrossEntropyLoss()\n",
343
+ "# Define optimizer\n",
344
+ "optimizer = Adam(model.parameters(), learning_rate)"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "source": [
353
+ "# Task 5: Start training for 20 epochs:\n",
354
+ "\n",
355
+ "train_losses = []\n",
356
+ "val_losses = []\n",
357
+ "val_accuracies = []\n",
358
+ "\n",
359
+ "print('Starting Training...')\n",
360
+ "for epoch in range(num_epochs):\n",
361
+ " # Train one epoch\n",
362
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
363
+ "\n",
364
+ " # Validate\n",
365
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
366
+ "\n",
367
+ " train_losses.append(train_loss)\n",
368
+ " val_losses.append(val_loss)\n",
369
+ " val_accuracies.append(val_accuracy)\n",
370
+ "\n",
371
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
372
+ "\n",
373
+ "print('Training Complete!')"
374
+ ],
375
+ "execution_count": null,
376
+ "outputs": []
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "metadata": {},
381
+ "source": [
382
+ "# Task 1: Write your code here:\n",
383
+ "# Plotting results\n",
384
+ "plt.figure(figsize=(7, 5))\n",
385
+ "\n",
386
+ "plt.plot(train_losses, label='Train Loss')\n",
387
+ "plt.plot(val_losses, label='Validation Loss')\n",
388
+ "plt.title('Loss over Epochs')\n",
389
+ "plt.xlabel('Epoch')\n",
390
+ "plt.ylabel('Loss (MSE)')\n",
391
+ "plt.legend()\n",
392
+ "\n",
393
+ "plt.tight_layout()\n",
394
+ "plt.show()"
395
+ ],
396
+ "execution_count": null,
397
+ "outputs": []
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "metadata": {},
402
+ "source": [
403
+ "# Task 2 (Bonus): Write your code here:\n",
404
+ "# Set model to evaluation mode\n",
405
+ "model.eval()\n",
406
+ "# Get one batch from the test DataLoader\n",
407
+ "images, labels = next(iter(test_loader))\n",
408
+ "# Move images to device\n",
409
+ "images = images.to(device)\n",
410
+ "labels = labels.to(device)\n",
411
+ "\n",
412
+ "with torch.no_grad():\n",
413
+ " # Flatten images before passing to the model\n",
414
+ " outputs = model(images.view(images.size(0), -1))\n",
415
+ " predictions = torch.argmax(outputs, dim=1)\n",
416
+ "\n",
417
+ "# Move tensors back to CPU for plotting\n",
418
+ "images = images.cpu()\n",
419
+ "labels = labels.cpu()\n",
420
+ "predictions = predictions.cpu()\n",
421
+ "\n",
422
+ "# Plot first 5 predictions\n",
423
+ "plt.figure(figsize=(8, 4))\n",
424
+ "for i in range(5):\n",
425
+ " plt.subplot(2, 3, i + 1)\n",
426
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
427
+ " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
428
+ " plt.axis('off')\n",
429
+ "\n",
430
+ "plt.tight_layout()\n",
431
+ "plt.show()"
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/374/Q3.ipynb ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os\n",
32
+ "\n",
33
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
34
+ "\n",
35
+ "df = pd.read_csv(csv_path)"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 2: Write your code here:\n",
45
+ "df.head()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 3: Write your code here:\n",
55
+ "df.info()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 4: Write your code here:\n",
65
+ "df.describe()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 1: Write your code here:\n",
75
+ "def check_missing_values(df):\n",
76
+ " missing_values = df.isnull().sum()\n",
77
+ " print(\"Missing Values per Column:\")\n",
78
+ " print(missing_values[missing_values > 0])\n",
79
+ " if missing_values.any():\n",
80
+ " print(\"\\nHandle Missing Values as needed.\")\n",
81
+ " else:\n",
82
+ " print(\"\\nNo Missing Values Found.\")\n",
83
+ "\n",
84
+ "check_missing_values(df)"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "nums_column = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n",
94
+ "for col in nums_column:\n",
95
+ " df[col] = df[col].fillna(df[col].mode()[0])"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "check_missing_values(df)"
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
+ "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
+ "\n",
124
+ "check_duplicates(df)"
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
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
135
+ "\n",
136
+ "print(\"Categorical Columns:\", list(categorical_cols))"
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
+ "from sklearn.preprocessing import StandardScaler\n",
147
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
148
+ "\n",
149
+ "scaler = StandardScaler()\n",
150
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
151
+ "df.head()"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 5: Write your code here:\n",
161
+ "df[\"Target\"].value_counts()"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "## The target is imbalanced"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "%pip install kagglehub catboost xgboost tqdm -q"
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.drop(\"Target\", axis=1).astype(float)\n",
190
+ "y = df['Target'].astype(float)"
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
+ "# we will use StratifiedKFold because the imbalance\n",
202
+ "from sklearn.model_selection import StratifiedKFold\n",
203
+ "from catboost import CatBoostRegressor\n"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "from sklearn.metrics import mean_absolute_error as sklearn_mae\n",
213
+ "\n",
214
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
215
+ "\n",
216
+ "mae_scores = []\n",
217
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
218
+ "\n",
219
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
220
+ " # indexing for each fold\n",
221
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
222
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
223
+ "\n",
224
+ " print(f\"Fold {fold}\")\n",
225
+ " print(\" X_train shape:\", X_train.shape)\n",
226
+ " print(\" X_test shape :\", X_test.shape)\n",
227
+ " print(\" y_train shape:\", y_train.shape)\n",
228
+ " print(\" y_test shape :\", y_test.shape)\n",
229
+ "\n",
230
+ "\n",
231
+ " model = CatBoostRegressor(verbose=0)\n",
232
+ "\n",
233
+ " model.fit(X_train, y_train)\n",
234
+ "\n",
235
+ " y_pred = model.predict(X_test)\n",
236
+ "\n",
237
+ " mae_scores.append(sklearn_mae(y_test, y_pred))\n",
238
+ "\n",
239
+ "mae_scores = np.array(mae_scores)\n",
240
+ "\n",
241
+ "print(f\"5-Fold Results:\")\n",
242
+ "print(f\"MAE: {mae_scores.mean():,.2f}\")"
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
+ }
submissions_extracted/375/Q1.ipynb ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)\n",
13
+ "\n",
14
+ "import numpy as np\n",
15
+ "import pandas as pd\n",
16
+ "import matplotlib.pyplot as plt\n",
17
+ "import os\n",
18
+ "import kagglehub\n",
19
+ "\n",
20
+ "from sklearn.model_selection import train_test_split, KFold\n",
21
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
22
+ "from sklearn.ensemble import RandomForestRegressor\n",
23
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
24
+ "\n",
25
+ "import warnings\n",
26
+ "warnings.filterwarnings('ignore')\n"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "# Task 1: Write your code here:\n",
36
+ "Q1_path = os.path.join(path, 'Q1_data.csv')\n",
37
+ "df = pd.read_csv(Q1_path)"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "df.head()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 3: Write your code here:\n",
57
+ "df.info()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 4: Write your code here:\n",
67
+ "df.describe()"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# Task 5: Write your code here:\n",
77
+ "plt.figure(figsize=(10, 5))\n",
78
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
79
+ "plt.title('Price Distribution')\n",
80
+ "plt.xlabel('Price')\n",
81
+ "plt.ylabel('Frequency')\n",
82
+ "plt.show()"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# Task 1: Write your code here:\n",
92
+ "df.drop(columns=['Order_ID'])"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# Task 2: Write your code here:\n",
102
+ "def check_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)\n",
112
+ "\n",
113
+ "\n",
114
+ "#drop rows with missing value\n",
115
+ "\n",
116
+ "df= df.dropna(subset=['Delivery_Time','Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs'])\n",
117
+ "print(\"Handling...\")\n",
118
+ "\n",
119
+ "check_missing_values(df)"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# 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)"
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
+ "\n",
150
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
151
+ "\n",
152
+ "from sklearn.preprocessing import LabelEncoder\n",
153
+ "\n",
154
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
155
+ "for col in categorical_cols:\n",
156
+ " print(f\"Encoding column: {col}\")\n",
157
+ " le = LabelEncoder()\n",
158
+ " df[col] = le.fit_transform(df[col])\n",
159
+ "df"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 5: Write your code here:\n",
169
+ "from sklearn.preprocessing import StandardScaler\n",
170
+ "\n",
171
+ "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
172
+ "\n",
173
+ "scaler = StandardScaler()\n",
174
+ "df[features] = scaler.fit_transform(df[features])\n",
175
+ "df.head()"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task 6: Write your code here:\n",
185
+ "# Task 5: Write your code here:\n",
186
+ "plt.figure(figsize=(10, 5))\n",
187
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
188
+ "plt.title('Price Distribution')\n",
189
+ "plt.xlabel('Price')\n",
190
+ "plt.ylabel('Frequency')\n",
191
+ "plt.show()"
192
+ ],
193
+ "execution_count": null,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "metadata": {},
199
+ "source": [
200
+ "# Task 1: Write your code here:\n",
201
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
202
+ "y = df['Delivery_Time'].astype(float)\n",
203
+ "X.head()"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Task 2,3,4,5: Write your code here:\n",
213
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
214
+ "\n",
215
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
216
+ " X, y,\n",
217
+ " test_size=0.2, # 20% for test, remaining 80% for train\n",
218
+ " random_state=42, # reproducible output\n",
219
+ " shuffle=True,) # representative splits\n",
220
+ "\n",
221
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
222
+ "\n",
223
+ "# Iterate through folds\n",
224
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
225
+ " # indexing for each fold\n",
226
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
227
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
228
+ " # print shapes\n",
229
+ " print(f\"Fold {fold}\")\n",
230
+ " print(\" X_train shape:\", X_train.shape)\n",
231
+ " print(\" X_test shape :\", X_test.shape)\n",
232
+ " print(\" y_train shape:\", y_train.shape)\n",
233
+ " print(\" y_test shape :\", y_test.shape)\n",
234
+ " print(\"-\" * 30)\n",
235
+ "\n",
236
+ "model = RandomForestRegressor(n_estimators=200)\n",
237
+ "\n",
238
+ "mse=[]\n",
239
+ "\n",
240
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
241
+ " print(f\"\\nFold {fold_idx + 1}/{5}\")\n",
242
+ "\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
+ " model.fit(X_train, y_train)\n",
248
+ "\n",
249
+ " y_pred = model.predict(X_test)\n",
250
+ "\n",
251
+ " mseval= mean_squared_error(y_test, y_pred)\n",
252
+ " print(mseval)\n",
253
+ " msev = mse.append(mseval)\n",
254
+ "\n",
255
+ "\n",
256
+ "\n",
257
+ "\n"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Task 1: Write your code here:\n",
267
+ "lr_model = model\n",
268
+ "# For multi-class, we can take the mean of the absolute coefficients across classes\n",
269
+ "feature_importances_lr = pd.Series(np.mean(np.abs(lr_model.coef_), axis=0), index=X.columns)\n",
270
+ "\n",
271
+ "# Extract sorted features and their coefficients\n",
272
+ "feature_importances_lr = feature_importances_lr.sort_values(ascending=False)\n",
273
+ "\n",
274
+ "# Plot feature importances\n",
275
+ "plt.figure(figsize=(10, 6))\n",
276
+ "sns.barplot(x=feature_importances_lr.values, y=feature_importances_lr.index)\n",
277
+ "plt.title('Logistic Regression Feature Importances (Absolute Mean Coefficients)')\n",
278
+ "plt.xlabel('Absolute Mean Coefficient Value')\n",
279
+ "plt.ylabel('Features')\n",
280
+ "plt.show()"
281
+ ],
282
+ "execution_count": null,
283
+ "outputs": []
284
+ },
285
+ {
286
+ "cell_type": "code",
287
+ "metadata": {},
288
+ "source": [
289
+ "# Task 2: Write your code here:"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "metadata": {},
297
+ "source": [
298
+ "# Task Bonus: Write your code here:"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ }
303
+ ],
304
+ "metadata": {
305
+ "kernelspec": {
306
+ "display_name": "Python 3",
307
+ "name": "python3"
308
+ },
309
+ "language_info": {
310
+ "name": "python"
311
+ }
312
+ },
313
+ "nbformat": 4,
314
+ "nbformat_minor": 0
315
+ }
submissions_extracted/375/Q2.ipynb ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/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
+ "import torch\n",
78
+ "import torch.nn as nn\n",
79
+ "from torch.optim import Adam\n",
80
+ "import matplotlib.pyplot as plt\n",
81
+ "from sklearn.datasets import load_breast_cancer\n",
82
+ "from sklearn.model_selection import train_test_split\n",
83
+ "from sklearn.preprocessing import StandardScaler\n",
84
+ "from torch.utils.data import TensorDataset\n",
85
+ "from torch.utils.data import DataLoader\n",
86
+ "\n",
87
+ "\n",
88
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
89
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
90
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
91
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
92
+ "\n",
93
+ "\n",
94
+ "\n"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# 2. Create TensorDataset objects\n",
104
+ "\n",
105
+ "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
+ "\n",
117
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
118
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\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}\")\n",
132
+ "\n"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# 5. Display sample images\n",
142
+ "# Get one batch of images and labels\n",
143
+ "images, labels = next(iter(train_loader))\n",
144
+ "\n",
145
+ "# Display the first 6 images in the batch\n",
146
+ "plt.figure(figsize=(8, 4))\n",
147
+ "\n",
148
+ "for i in range(6):\n",
149
+ " plt.subplot(2, 3, i + 1)\n",
150
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
151
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
152
+ " plt.axis('off')\n",
153
+ "\n",
154
+ "plt.tight_layout()\n",
155
+ "plt.show()\n",
156
+ "\n"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 1: Write your model class here:\n",
166
+ "class NN4Layer(nn.Module):\n",
167
+ " def __init__(self, input_dim, hidden_dim):\n",
168
+ " super(NN4Layer, self).__init__()\n",
169
+ " # TODO: Define the first linear layer: input_dim -> hidden_dim\n",
170
+ " self.layer1 = nn.Linear(input_dim, hidden_dim) # <Replace None with your code>\n",
171
+ "\n",
172
+ " # TODO: Define the second linear layer: hidden_dim -> hidden_dim\n",
173
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
174
+ "\n",
175
+ " # TODO: Define the third linear layer: hidden_dim -> hidden_dim\n",
176
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
177
+ "\n",
178
+ " # TODO: Define the output layer: hidden_dim -> 1 (single value for regression)\n",
179
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
180
+ "\n",
181
+ " # TODO: Define ReLU activation\n",
182
+ " self.relu = nn.ReLU() # <Replace None with your code>\n",
183
+ "\n",
184
+ " def forward(self, x):\n",
185
+ " # TODO: First hidden layer with ReLU\n",
186
+ " a1 = self.relu(self.layer1(x)) # <Replace None with your code>\n",
187
+ "\n",
188
+ " # TODO: Second hidden layer with ReLU\n",
189
+ " a2 = self.relu(self.layer2(a1)) # <Replace None with your code>\n",
190
+ "\n",
191
+ " # TODO: Output layer (no activation for regression)\n",
192
+ " output = self.layer3(a2) # <Replace None with your code>\n",
193
+ "\n",
194
+ " return output"
195
+ ],
196
+ "execution_count": null,
197
+ "outputs": []
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "metadata": {},
202
+ "source": [
203
+ "# Task 2: Write your training loop here:\n",
204
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
205
+ " # TODO: Set the model to training mode\n",
206
+ " # <YOUR CODE HERE>\n",
207
+ " model.train()\n",
208
+ "\n",
209
+ " running_loss = 0.0\n",
210
+ "\n",
211
+ " for X_batch, y_batch in train_loader:\n",
212
+ " # TODO: Move batch to the selected device\n",
213
+ " X_batch = X_batch.to(device)\n",
214
+ " y_batch = y_batch.to(device).reshape(-1, 1) # Reshape y_batch here\n",
215
+ "\n",
216
+ " # TODO: Forward pass - get model predictions\n",
217
+ " outputs = model(X_batch) # <Replace None with your code>\n",
218
+ "\n",
219
+ " # TODO: Compute loss using criterion\n",
220
+ " loss = criterion(outputs, y_batch) # <Replace None with your code>\n",
221
+ "\n",
222
+ " # TODO: Backward pass & optimization\n",
223
+ " # Step 1: Clear previous gradients\n",
224
+ " # <YOUR CODE HERE>\n",
225
+ " optimizer.zero_grad()\n",
226
+ "\n",
227
+ " # Step 2: Compute gradients (backward pass)\n",
228
+ " # <YOUR CODE HERE>\n",
229
+ " loss.backward()\n",
230
+ "\n",
231
+ " # Step 3: Update model parameters\n",
232
+ " # <YOUR CODE HERE>\n",
233
+ " optimizer.step()\n",
234
+ "\n",
235
+ " running_loss += loss.item()\n",
236
+ "\n",
237
+ " # Calculate average loss over all batches\n",
238
+ " avg_loss = running_loss / len(train_loader)\n",
239
+ "\n",
240
+ " return avg_loss\n"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": []
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "metadata": {},
248
+ "source": [
249
+ "# Task 3: Write your validation loop here:\n",
250
+ "def validate(model, criterion, test_loader, device):\n",
251
+ " # TODO: Set the model to evaluation mode\n",
252
+ " # <YOUR CODE HERE>\n",
253
+ " model.eval()\n",
254
+ "\n",
255
+ " running_loss = 0.0\n",
256
+ "\n",
257
+ " # TODO: Disable gradient computation using torch.no_grad()\n",
258
+ " with torch.no_grad():\n",
259
+ " for X_batch, y_batch in test_loader:\n",
260
+ " # TODO: Move data to device\n",
261
+ " X_batch = X_batch.to(device)\n",
262
+ " y_batch = y_batch.to(device).reshape(-1, 1) # Reshape y_batch here\n",
263
+ "\n",
264
+ " # TODO: Forward pass - get model predictions\n",
265
+ " outputs = model(X_batch) # <Replace None with your code>\n",
266
+ "\n",
267
+ " # TODO: Compute loss using criterion\n",
268
+ " loss = criterion(outputs, y_batch) # <Replace None with your code>\n",
269
+ "\n",
270
+ " running_loss += loss.item()\n",
271
+ "\n",
272
+ " avg_loss = running_loss / len(test_loader)\n",
273
+ "\n",
274
+ " return avg_loss"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "# Task 4: Define device, model, loss, optimizer:\n",
284
+ "from torch.optim import Adam\n",
285
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
286
+ "learning_rate=0.01\n",
287
+ "# Model parameters\n",
288
+ "input_dim = X_train.shape[1]\n",
289
+ "hidden_dim = 64\n",
290
+ "\n",
291
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
292
+ "\n",
293
+ "criterion = nn.MSELoss()\n",
294
+ "\n",
295
+ "optimizer = Adam(model.parameters(), learning_rate)\n"
296
+ ],
297
+ "execution_count": null,
298
+ "outputs": []
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "metadata": {},
303
+ "source": [
304
+ "# Task 5: Start training for 20 epochs:\n",
305
+ "num_epochs = 20\n",
306
+ "# Run Training\n",
307
+ "train_losses = []\n",
308
+ "val_losses = []\n",
309
+ "\n",
310
+ "print('Starting Training...')\n",
311
+ "for epoch in range(num_epochs):\n",
312
+ " # TODO: Train one epoch using the train_one_epoch function\n",
313
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device) # <Replace None with your code>\n",
314
+ "\n",
315
+ " # TODO: Validate using the validate function\n",
316
+ " val_loss = validate(model, criterion, test_loader, device) # <Replace None with your code>\n",
317
+ "\n",
318
+ " train_losses.append(train_loss)\n",
319
+ " val_losses.append(val_loss)\n",
320
+ "\n",
321
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
322
+ "\n",
323
+ "print('Training Complete!')"
324
+ ],
325
+ "execution_count": null,
326
+ "outputs": []
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "metadata": {},
331
+ "source": [
332
+ "# Task 1: Write your code here:\n",
333
+ "plt.figure(figsize=(7, 5))\n",
334
+ "\n",
335
+ "plt.plot(train_losses, label='Train Loss')\n",
336
+ "plt.plot(val_losses, label='Validation Loss')\n",
337
+ "plt.title('Loss over Epochs')\n",
338
+ "plt.xlabel('Epoch')\n",
339
+ "plt.ylabel('Loss (MSE)')\n",
340
+ "plt.legend()\n",
341
+ "\n",
342
+ "plt.tight_layout()\n",
343
+ "plt.show()"
344
+ ],
345
+ "execution_count": null,
346
+ "outputs": []
347
+ },
348
+ {
349
+ "cell_type": "code",
350
+ "metadata": {},
351
+ "source": [
352
+ "# Task 2 (Bonus): Write your code here:"
353
+ ],
354
+ "execution_count": null,
355
+ "outputs": []
356
+ }
357
+ ],
358
+ "metadata": {
359
+ "kernelspec": {
360
+ "display_name": "Python 3",
361
+ "name": "python3"
362
+ },
363
+ "language_info": {
364
+ "name": "python"
365
+ }
366
+ },
367
+ "nbformat": 4,
368
+ "nbformat_minor": 0
369
+ }
submissions_extracted/375/Q3.ipynb ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
36
+ "\n",
37
+ "df = pd.read_csv(csv_path)\n"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "df.head()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 3: Write your code here:\n",
57
+ "df.info()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 4: Write your code here:\n",
67
+ "df.describe()"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "from queue import Empty\n",
77
+ "# Task 1: Write your code here:\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)\n",
88
+ "\n",
89
+ "Empty = df.select.isnull(df)\n",
90
+ "\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# Task 2: Write your code here:\n",
102
+ "def check_duplicates(df):\n",
103
+ " duplicates = df.duplicated().sum()\n",
104
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
105
+ " if duplicates > 0:\n",
106
+ " print(\"Dropping Duplicates...\")\n",
107
+ " df.drop_duplicates(inplace=True)\n",
108
+ " print(\"Duplicates Dropped.\")\n",
109
+ " else:\n",
110
+ " print(\"No Duplicate Samples Found.\")\n",
111
+ "\n",
112
+ "check_duplicates(df)"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 3: Write your code here:\n",
122
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
123
+ "\n",
124
+ "from sklearn.preprocessing import LabelEncoder\n",
125
+ "\n",
126
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
127
+ "for col in categorical_cols:\n",
128
+ " print(f\"Encoding column: {col}\")\n",
129
+ " le = LabelEncoder()\n",
130
+ " df[col] = le.fit_transform(df[col])\n",
131
+ "df"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 4: Write your code here:\n",
141
+ "from sklearn.preprocessing import StandardScaler\n",
142
+ "\n",
143
+ "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
144
+ "\n",
145
+ "scaler = StandardScaler()\n",
146
+ "df[features] = scaler.fit_transform(df[features])\n",
147
+ "df.head()"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 5: Write your code here:\n",
157
+ "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
+ "\n",
164
+ "check_target_imbalance(df, \"Target\")"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 1: Write your code here:\n",
174
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
175
+ "y = df['Target'].astype(float)"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task 2,3,4,5: Write your code here:\n",
185
+ "from sklearn.model_selection import StratifiedKFold\n",
186
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
187
+ "from sklearn.linear_model import LogisticRegression\n",
188
+ "\n",
189
+ "n_splits = 5\n",
190
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
191
+ "\n",
192
+ "lr_losses = []\n",
193
+ "lr_accuracy = []\n",
194
+ "lr_precision = []\n",
195
+ "lr_recall = []\n",
196
+ "lr_f1 = []\n",
197
+ "\n",
198
+ "model = LogisticRegression()\n",
199
+ "\n",
200
+ "for train_index, test_index in skf.split(X, y):\n",
201
+ " # Split data into training and testing sets\n",
202
+ " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
203
+ " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
204
+ " # Train the model\n",
205
+ " model.fit(X_Train, y_Train)\n",
206
+ " # Predict on the test set\n",
207
+ " y_pred = model.predict(X_Test)"
208
+ ],
209
+ "execution_count": null,
210
+ "outputs": []
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "metadata": {},
215
+ "source": [
216
+ "# Task 1: Write your code here:\n",
217
+ "lr_model = model\n",
218
+ "# For multi-class, we can take the mean of the absolute coefficients across classes\n",
219
+ "feature_importances_lr = pd.Series(np.mean(np.abs(lr_model), axis=0), index=X.columns)\n",
220
+ "\n",
221
+ "# Extract sorted features and their coefficients\n",
222
+ "feature_importances_lr = feature_importances_lr.sort_values(ascending=False)\n",
223
+ "\n",
224
+ "# Plot feature importances\n",
225
+ "plt.figure(figsize=(10, 6))\n",
226
+ "sns.barplot(x=feature_importances_lr.values, y=feature_importances_lr.index)\n",
227
+ "plt.title('Logistic Regression Feature Importances (Absolute Mean Coefficients)')\n",
228
+ "plt.xlabel('Absolute Mean Coefficient Value')\n",
229
+ "plt.ylabel('Features')\n",
230
+ "plt.show()"
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "metadata": {},
238
+ "source": [
239
+ "# Task 2: Write your code here:"
240
+ ],
241
+ "execution_count": null,
242
+ "outputs": []
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "metadata": {},
247
+ "source": [
248
+ "# Task Bonus: Write your code here:"
249
+ ],
250
+ "execution_count": null,
251
+ "outputs": []
252
+ }
253
+ ],
254
+ "metadata": {
255
+ "kernelspec": {
256
+ "display_name": "Python 3",
257
+ "name": "python3"
258
+ },
259
+ "language_info": {
260
+ "name": "python"
261
+ }
262
+ },
263
+ "nbformat": 4,
264
+ "nbformat_minor": 0
265
+ }
submissions_extracted/376/Q1.ipynb ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestClassifier\n",
16
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')"
20
+ ],
21
+ "execution_count": null,
22
+ "outputs": []
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "source": [
28
+ "# Download latest version\n",
29
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
30
+ "\n",
31
+ "print(\"Path to dataset files:\", path)"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 1: Write your code here:\n",
41
+ "# Load the dataset\n",
42
+ "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n",
43
+ "df_Q1_data = pd.read_csv(Q1_data_path)"
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
+ "print(f\"Dataset shape: {df_Q1_data.shape}\")\n",
54
+ "df_Q1_data.head()"
55
+ ],
56
+ "execution_count": null,
57
+ "outputs": []
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "# Task 3: Write your code here:\n",
64
+ "# Check data types and structure\n",
65
+ "df_Q1_data.info()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 4: Write your code here:\n",
75
+ "# Descriptive statistics for numerical columns\n",
76
+ "df_Q1_data.describe()"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# Task 5: Write your code here:\n",
86
+ "def check_target_distribution(df_Q1_data, target_column):\n",
87
+ " df_Q1_data[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(\"Delievery time\")\n",
92
+ " plt.grid(False)\n",
93
+ "\n",
94
+ " plt.show()"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 1: Write your code here:\n",
104
+ "df_Q1_data.drop(columns=['Order_ID'])"
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
+ "def check_missing_values(df_Q1_data):\n",
115
+ " missing_values = df_Q1_data.isnull().sum()\n",
116
+ " print(\"Missing Values per Column:\")\n",
117
+ " print(missing_values[missing_values > 0])\n",
118
+ " if missing_values.any():\n",
119
+ " print(\"\\nHandle Missing Values as needed.\")\n",
120
+ " else:\n",
121
+ " print(\"\\nNo Missing Values Found.\")\n",
122
+ "\n",
123
+ "check_missing_values(df_Q1_data)"
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
+ "def check_duplicates(df_Q1_data):\n",
134
+ " duplicates = df_Q1_data.duplicated().sum()\n",
135
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
136
+ " if duplicates > 0:\n",
137
+ " print(\"Dropping Duplicates...\")\n",
138
+ " df_Q1_data.drop_duplicates(inplace=True)\n",
139
+ " print(\"Duplicates Dropped.\")\n",
140
+ " else:\n",
141
+ " print(\"No Duplicate Samples Found.\")\n",
142
+ "\n",
143
+ "check_duplicates(df_Q1_data)"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "# Task 4: Write your code here:\n",
153
+ "\n",
154
+ "categorical_cols = df_Q1_data.select_dtypes(include=[\"object\"]).columns\n",
155
+ "\n",
156
+ "print(\"Categorical Columns:\", list(categorical_cols))"
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\n",
167
+ "\n",
168
+ "numerical_cols = df_Q1_data.select_dtypes(include=[\"int64\", \"float64\"]df_Q1_data).columns.drop(\"status\")\n",
169
+ "\n",
170
+ "scaler = StandardScaler()\n",
171
+ "df_Q1_data[numerical_cols] = scaler.fit_transform([numerical_cols])\n",
172
+ "df_Q1_data.head()"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 6: Write your code here:\n",
182
+ "def check_target_imbalance(df_Q1_data):\n",
183
+ " print(\"Target Distribution:\")\n",
184
+ " print(df_Q1_data[target_column].value_counts(normalize=True))\n",
185
+ " sns.countplot(x=df[target_column])\n",
186
+ " plt.title(\"Target Distribution\")\n",
187
+ " plt.show()\n",
188
+ "\n",
189
+ "check_target_imbalance(df_Q1_data, \"delivery_time\")"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "from sklearn.model_selection import StratifiedKFold\n",
199
+ "from sklearn.metrics import accuracy_score, f1_score"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "# Task 1: Write your code here:\n",
209
+ "# Define features (X) and target (y)\n",
210
+ "feature_cols = [ 'delivery distance', 'restaurant preparation time\", \"traffic conditions', 'order details'\n",
211
+ "\n",
212
+ "]\n",
213
+ "\n",
214
+ "X = df_Q1_data_clean[feature_cols]\n",
215
+ "y = df_Q1_data_clean['delievery time']"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "from sklearn.ensemble import RandomForestRegressor\n",
225
+ "\n",
226
+ "# Task 2,3,4,5: Write your code here:\n",
227
+ "#Task 2\n",
228
+ "n_splits = 3 # K=3 Folds\n",
229
+ "\n",
230
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
231
+ "# Task 3\n",
232
+ "# Train Random Forest Regressor\n",
233
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
234
+ "model.fit(X_train_scaled, y_train)\n",
235
+ "print(\"Model trained!\")\n",
236
+ "\n",
237
+ "# Task 4\n",
238
+ "# Get predictions on test set\n",
239
+ "model.eval()\n",
240
+ "with torch.no_grad():\n",
241
+ " # TODO: Get predictions for X_test\n",
242
+ " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n",
243
+ " predictions = model(X_test.to(device)).cpu().numpy()\n",
244
+ "\n",
245
+ "# TODO: Calculate evaluation metrics\n",
246
+ "mae = mean_absolute_error(y_test.numpy(), p\n",
247
+ "\n",
248
+ "# Task 5\n",
249
+ "for model_name in all_results:\n",
250
+ " print(f\"\\n{model_name}:\")\n",
251
+ " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
252
+ " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
253
+ " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
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\n",
264
+ "importance = pd.DataFrame({\n",
265
+ " 'feature': feature_cols,\n",
266
+ " 'importance': model.feature_importances_\n",
267
+ "}).sort_values('importance', ascending=False)\n",
268
+ "\n",
269
+ "plt.figure(figsize=(10, 6))\n",
270
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
271
+ "plt.xlabel('Importance')\n",
272
+ "plt.title('Feature Importance')\n",
273
+ "plt.gca().invert_yaxis()\n",
274
+ "plt.show()"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "# Task 2: Write your code here:\n",
284
+ "def check_target_distribution(df_Q1_data, target_column):\n",
285
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
286
+ "\n",
287
+ " plt.title(f\"minutes ({target_column})\")\n",
288
+ " plt.xlabel(target_column)\n",
289
+ " plt.ylabel(\"delievery time\")\n",
290
+ " plt.grid(False)\n",
291
+ "\n",
292
+ " plt.show()\n",
293
+ "\n",
294
+ "check_target_distribution(df_Q1_data, \"delievery time\")"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {},
302
+ "source": [
303
+ "# Task Bonus: Write your code here:"
304
+ ],
305
+ "execution_count": null,
306
+ "outputs": []
307
+ }
308
+ ],
309
+ "metadata": {
310
+ "kernelspec": {
311
+ "display_name": "Python 3",
312
+ "name": "python3"
313
+ },
314
+ "language_info": {
315
+ "name": "python"
316
+ }
317
+ },
318
+ "nbformat": 4,
319
+ "nbformat_minor": 0
320
+ }
submissions_extracted/376/Q2.ipynb ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Import required libraries\n",
69
+ "import kagglehub\n",
70
+ "import pandas as pd\n",
71
+ "import numpy as np\n",
72
+ "import torch\n",
73
+ "import torch.nn as nn\n",
74
+ "from torch.optim import AdamW\n",
75
+ "import matplotlib.pyplot as plt\n",
76
+ "from torch.utils.data import DataLoader, TensorDataset\n",
77
+ "from sklearn.model_selection import train_test_split\n",
78
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
79
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
89
+ "# TODO: Split features from target\n",
90
+ "X = df_img_dir.drop(\"age\",axis=1)\n",
91
+ "y = df_img_dir['age']\n",
92
+ "\n",
93
+ "# TODO: Split the dataset into training and testing sets (80% train, 20% test)\n",
94
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
95
+ "\n",
96
+ "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n",
97
+ "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
98
+ "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
99
+ "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n",
100
+ "y_test = torch.tensor(y_test.values, dtype=torch.float32)"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# 2. Create TensorDataset objects\n",
110
+ "# Create TensorDatasets for training and testing\n",
111
+ "train_dataset = TensorDataset(X_train, y_train)\n",
112
+ "test_dataset = TensorDataset(X_test, y_test)\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# 3. Create DataLoaders\n",
122
+ "# Create Dataloaders to train and test data in batches\n",
123
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
124
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# 4. Print shape of one batch\n",
134
+ "\n",
135
+ "# Get the first batch from the training DataLoader\n",
136
+ "X_batch, y_batch = next(iter(train_loader))\n",
137
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
138
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n",
139
+ "\n"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# 5. Display sample images\n",
149
+ "from torchvision.datasets import MNIST\n",
150
+ "from torchvision.transforms.functional import to_tensor\n",
151
+ "\n",
152
+ "# Training dataset\n",
153
+ "train_dataset = MNIST(\n",
154
+ " root='./datasets', # Dataset storage path\n",
155
+ " train=True, # Use training data\n",
156
+ " transform=to_tensor, # Convert images to tensors\n",
157
+ " download=True # Download if not available\n",
158
+ ")\n",
159
+ "\n",
160
+ "# Testing dataset\n",
161
+ "test_dataset = MNIST(\n",
162
+ " root='./datasets', # Dataset storage path\n",
163
+ " train=False, # Use test data\n",
164
+ " transform=to_tensor, # Convert images to tensors\n",
165
+ " download=True # Download if not available\n",
166
+ ")\n",
167
+ "\n",
168
+ "# print one sample from the dataset\n",
169
+ "# Each sample consists of an image tensor and its label\n",
170
+ "sample_image, sample_label = train_dataset[0]\n",
171
+ "\n",
172
+ "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
173
+ "print(f\"Label: {sample_label}\")\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 model class here:\n",
184
+ "class NN5Layer(nn.Module):\n",
185
+ "\n",
186
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
187
+ " super(NN5Layer, self).__init__()\n",
188
+ "\n",
189
+ " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
190
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
191
+ "\n",
192
+ " # TODO: What are the dimensions from previous and next layer?\n",
193
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
194
+ "\n",
195
+ " # TODO: What are the dimensions from previous and next layer?\n",
196
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
197
+ "\n",
198
+ " # TODO: What are the dimensions from previous and next layer?\n",
199
+ " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
200
+ "\n",
201
+ " # Defines how input data flows through the network\n",
202
+ " def forward(self, x):\n",
203
+ " # Layer 1: TODO\n",
204
+ " z1 = self.layer1(x)\n",
205
+ " a1 = self.relu(z1)\n",
206
+ "\n",
207
+ " # Layer 2 TODO\n",
208
+ " z2 = self.layer2(a1)\n",
209
+ " a2 = self.relu(z2)\n",
210
+ "\n",
211
+ " # Layer 3 TODO\n",
212
+ " z3 = self.layer3(a2)\n",
213
+ " a3 = self.relu(z3)\n",
214
+ "\n",
215
+ " # Layer 4 TODO\n",
216
+ " z4 = self.layer4(a3)\n",
217
+ " a4 = self.relu(z4)\n"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 2: Write your training loop here:\n",
227
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
228
+ " # Set the model to training mode\n",
229
+ " model.train()\n",
230
+ "\n",
231
+ " running_loss = 0.0\n",
232
+ "\n",
233
+ " for X_batch, y_batch in train_loader:\n",
234
+ " # Move batch to the selected device\n",
235
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
236
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
237
+ "\n",
238
+ " # Forward pass (outputs are logits)\n",
239
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
240
+ " loss = criterion(outputs, y_batch)\n",
241
+ "\n",
242
+ " # Backward pass & optimization\n",
243
+ " optimizer.zero_grad() # Clear previous gradients\n",
244
+ " loss.backward() # Compute gradients\n",
245
+ " optimizer.step() # Update model parameters\n",
246
+ "\n",
247
+ " running_loss += loss.item()\n",
248
+ "\n",
249
+ " # Average loss over all batches\n",
250
+ " avg_loss = running_loss / len(train_loader)\n",
251
+ "\n",
252
+ " return avg_loss"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 3: Write your validation loop here:\n",
262
+ "def validate(model, criterion, test_loader, device):\n",
263
+ " # Set the model to evaluation mode\n",
264
+ " model.eval()\n",
265
+ "\n",
266
+ " running_loss = 0.0\n",
267
+ " correct = 0\n",
268
+ " total = 0\n",
269
+ "\n",
270
+ " with torch.no_grad():\n",
271
+ " for X_batch, y_batch in test_loader:\n",
272
+ " # Move data to device\n",
273
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
274
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
275
+ "\n",
276
+ " # Forward pass\n",
277
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
278
+ " loss = criterion(outputs, y_batch)\n",
279
+ " running_loss += loss.item()\n",
280
+ "\n",
281
+ " # Apply Softmax to get probabilities\n",
282
+ " probabilities = F.softmax(outputs, dim=1)\n",
283
+ "\n",
284
+ " # Pick the classes with highest probabilities\n",
285
+ " predicted = torch.argmax(probabilities, dim=1)\n",
286
+ "\n",
287
+ " # Accuracy calculation\n",
288
+ " correct += (predicted == y_batch).sum().item()\n",
289
+ " total += y_batch.size(0)\n",
290
+ "\n",
291
+ " avg_loss = running_loss / len(test_loader)\n",
292
+ " accuracy = correct / total\n",
293
+ "\n",
294
+ " return avg_loss, accuracy"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {},
302
+ "source": [
303
+ "# Device setup\n",
304
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
305
+ "\n",
306
+ "# Model parameters\n",
307
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
308
+ "hidden_dim = 14 # Design choice\n",
309
+ "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
310
+ "\n",
311
+ "# Instantiate model\n",
312
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
313
+ "\n",
314
+ "# Print the model architecture\n",
315
+ "print(\"Model Architecture:\\n\")\n",
316
+ "print(model)\n",
317
+ "\n",
318
+ "# Calculate the total number of trainable parameters\n",
319
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
320
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
321
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
322
+ "criterion = nn.CrossEntropyLoss()\n",
323
+ "# Define optimizer\n",
324
+ "optimizer = AdamW(model.parameters(), learning_rate)"
325
+ ],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "metadata": {},
332
+ "source": [
333
+ "# Task 5: Start training for 20 epochs:\n",
334
+ "# Run Training\n",
335
+ "train_losses = []\n",
336
+ "val_losses = []\n",
337
+ "val_accuracies = []\n",
338
+ "\n",
339
+ "print('Starting Training...')\n",
340
+ "for epoch in range(num_epochs):\n",
341
+ " # Train one epoch\n",
342
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
343
+ "\n",
344
+ " # Validate\n",
345
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
346
+ "\n",
347
+ " train_losses.append(train_loss)\n",
348
+ " val_losses.append(val_loss)\n",
349
+ " val_accuracies.append(val_accuracy)\n",
350
+ "\n",
351
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
352
+ "\n",
353
+ "print('Training Complete!')\n",
354
+ "\n",
355
+ "num_epochs = 20\n",
356
+ "learning_rate = 0.001\n",
357
+ "\n",
358
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
359
+ "criterion = nn.CrossEntropyLoss()\n",
360
+ "# Define optimizer\n",
361
+ "optimizer = AdamW(model.parameters(), learning_rate)"
362
+ ],
363
+ "execution_count": null,
364
+ "outputs": []
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "metadata": {},
369
+ "source": [
370
+ "# Task 1: Write your code here:\n",
371
+ "# Plotting results\n",
372
+ "plt.figure(figsize=(7, 5))\n",
373
+ "\n",
374
+ "plt.plot(train_losses, label='Train Loss')\n",
375
+ "plt.plot(val_losses, label='Validation Loss')\n",
376
+ "plt.title('Loss over Epochs')\n",
377
+ "plt.xlabel('Epoch')\n",
378
+ "plt.ylabel('Loss')\n",
379
+ "plt.legend()\n",
380
+ "\n",
381
+ "plt.tight_layout()\n",
382
+ "plt.show()"
383
+ ],
384
+ "execution_count": null,
385
+ "outputs": []
386
+ },
387
+ {
388
+ "cell_type": "code",
389
+ "metadata": {},
390
+ "source": [
391
+ "# Task 2 (Bonus): Write your code here:"
392
+ ],
393
+ "execution_count": null,
394
+ "outputs": []
395
+ }
396
+ ],
397
+ "metadata": {
398
+ "kernelspec": {
399
+ "display_name": "Python 3",
400
+ "name": "python3"
401
+ },
402
+ "language_info": {
403
+ "name": "python"
404
+ }
405
+ },
406
+ "nbformat": 4,
407
+ "nbformat_minor": 0
408
+ }
submissions_extracted/376/Q3.ipynb ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestClassifier\n",
16
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')"
20
+ ],
21
+ "execution_count": null,
22
+ "outputs": []
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "source": [
28
+ "import kagglehub\n",
29
+ "\n",
30
+ "\n",
31
+ "\n",
32
+ "# Download latest version\n",
33
+ "\n",
34
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
35
+ "\n",
36
+ "\n",
37
+ "\n",
38
+ "print(\"Path to dataset files:\", path)"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 1: Write your code here:\n",
48
+ "\n",
49
+ "# Load the dataset\n",
50
+ "Q3_data_path = os.path.join(path, 'Q3_data.csv')\n",
51
+ "df_Q3_data = pd.read_csv(Q3_data_path)"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 2: Write your code here:\n",
61
+ "print(f\"Dataset shape: {df_Q3_data.shape}\")\n",
62
+ "df_Q3_data.head()"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 3: Write your code here:\n",
72
+ "# Check data types and structure\n",
73
+ "df_Q3_data.info()"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# Task 4: Write your code here:\n",
83
+ "# Descriptive statistics for numerical columns\n",
84
+ "df_Q3_data.describe()"
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
+ "def check_missing_values(df_Q3_data):\n",
95
+ " missing_values = df_Q3_data.isnull().sum()\n",
96
+ " print(\"Missing Values per Column:\")\n",
97
+ " print(missing_values[missing_values > 0])\n",
98
+ " if missing_values.any():\n",
99
+ " print(\"\\nHandle Missing Values as needed.\")\n",
100
+ " else:\n",
101
+ " print(\"\\nNo Missing Values Found.\")\n",
102
+ "\n",
103
+ "check_missing_values(df_Q3_data)"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 2: Write your code here:\n",
113
+ "def check_duplicates(df_Q3_data):\n",
114
+ " duplicates = df_Q3_data.duplicated().sum()\n",
115
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
116
+ " if duplicates > 0:\n",
117
+ " print(\"Dropping Duplicates...\")\n",
118
+ " df_Q1_data.drop_duplicates(inplace=True)\n",
119
+ " print(\"Duplicates Dropped.\")\n",
120
+ " else:\n",
121
+ " print(\"No Duplicate Samples Found.\")\n",
122
+ "\n",
123
+ "check_duplicates(df_Q3_data)"
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
+ "categorical_cols = df_Q3_data.select_dtypes(include=[\"object\"]).columns\n",
134
+ "\n",
135
+ "print(\"Categorical Columns:\", list(categorical_cols))"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# Task 4: Write your code here:"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "# Task 5: Write your code here:\n",
154
+ "def check_target_imbalance(df_Q3_data, target_column):\n",
155
+ " print(\"Target Distribution:\")\n",
156
+ "\n",
157
+ " df_Q3_data[target_column].hist()\n",
158
+ " plt.show()\n",
159
+ "\n",
160
+ "check_target_imbalance(df_Q3_data, \"P_2\")"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "# Task 1: Write your code here:\n",
170
+ "\n",
171
+ "from sklearn.model_selection import train_test_split\n",
172
+ "\n",
173
+ "X_clf = pd.df_Q3_data({\"Feature_1\": np.random.randn(500)}) # features\n",
174
+ "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1 y: 0 if X < 0 else 1\n",
175
+ "\n",
176
+ "# Use previously generated random data (example: classification data)\n",
177
+ "X, y = X_clf.copy(), y_clf.copy() # to make seperation from both copies of data (so original dats doesn't change)\n",
178
+ "\n",
179
+ "# split ratio (80% train, 20% test)\n",
180
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
181
+ " X, y,\n",
182
+ " test_size=0.2, # 20% for test, remaining 80% for train\n",
183
+ " random_state=42, # reproducible output = same results everytime\n",
184
+ " shuffle=True, # representative splits = mix up the data first, then split\n",
185
+ " stratify=y # preserve class distribution = keep the same class ratio in both train and rest\n",
186
+ ")\n",
187
+ "# With stratify\n",
188
+ "# train 60% class 0, 40% class 1\n",
189
+ "# Test: 60% class 0, $0# class 1\n",
190
+ "\n",
191
+ "# Print shapes\n",
192
+ "print(\"X_train shape:\", X_train.shape)\n",
193
+ "print(\"X_test shape:\", X_test.shape)\n",
194
+ "print(\"y_train shape:\", y_train.shape)\n",
195
+ "print(\"y_test shape:\", y_test.shape) # because 1D we didn't place something after the comma"
196
+ ],
197
+ "execution_count": null,
198
+ "outputs": []
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "metadata": {},
203
+ "source": [
204
+ "# Import models\n",
205
+ "from sklearn.linear_model import LogisticRegression\n",
206
+ "from sklearn.neighbors import KNeighborsClassifier\n",
207
+ "from sklearn.svm import SVC\n",
208
+ "from sklearn.tree import DecisionTreeClassifier\n",
209
+ "from sklearn.ensemble import RandomForestClassifier\n",
210
+ "from xgboost import XGBClassifier\n",
211
+ "from catboost import CatBoostClassifier\n",
212
+ "# Task 2,3,4,5: Write your code here:\n",
213
+ "# Task 2\n",
214
+ "\n",
215
+ "from sklearn.model_selection import StratifiedKFold\n",
216
+ "from sklearn.metrics import accuracy_score, f1_score\n",
217
+ "\n",
218
+ "n_splits = 3 # K=3 Folds\n",
219
+ "\n",
220
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
221
+ "\n",
222
+ "# Task 3 CatBoostClassifier\n",
223
+ " \"CatBoost\": CatBoostClassifier(\n",
224
+ " verbose=0,\n",
225
+ " n_estimators=200,\n",
226
+ " max_depth=4\n",
227
+ " )\n",
228
+ "}\n",
229
+ "\n",
230
+ "# Task 4\n",
231
+ "# Calculate evaluation metrics\n",
232
+ " accuracy = accuracy_score(y_test, y_pred)\n",
233
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n",
234
+ "\n",
235
+ " # Store results\n",
236
+ " sr_results['loss'].append(losses)\n",
237
+ " sr_results['acc'].append(accuracy)\n",
238
+ " sr_results['f1'].append(f1)\n",
239
+ "\n",
240
+ " # Task 5\n",
241
+ " # Print the average of each evaluation metric across folds\n",
242
+ " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n",
243
+ " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "metadata": {},
251
+ "source": [
252
+ "# Import models\n",
253
+ "from sklearn.neighbors import KNeighborsClassifier\n",
254
+ "from sklearn.svm import SVC\n",
255
+ "from sklearn.tree import DecisionTreeClassifier\n",
256
+ "from sklearn.ensemble import RandomForestClassifier\n",
257
+ "from xgboost import XGBClassifier\n",
258
+ "from catboost import CatBoostClassifier"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task 1: Write your code here:\n",
268
+ "sklearn_models = {\n",
269
+ " \"K-Nearest Neighbors\": KNeighborsClassifier(\n",
270
+ " n_neighbors=3, # Number of neighbors to consider\n",
271
+ " ),\n",
272
+ " \"Support Vector Machine\": SVC(\n",
273
+ " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n",
274
+ " C=0.75 # Regularization parameter\n",
275
+ " ),\n",
276
+ " \"Decision Tree\": DecisionTreeClassifier(\n",
277
+ " max_depth=3 # Maximum depth of tree (prevents overfitting)\n",
278
+ " ),\n",
279
+ " \"Random Forest\": RandomForestClassifier(\n",
280
+ " n_estimators=320, # Number of trees\n",
281
+ " max_depth=4\n",
282
+ " ),\n",
283
+ " \"XGBoost\": XGBClassifier(\n",
284
+ " verbosity=0,\n",
285
+ " n_estimators=300, # Number of boosting rounds\n",
286
+ " max_depth=5,\n",
287
+ " learning_rate=0.05 # Step size shrinkage\n",
288
+ " ),\n",
289
+ " \"CatBoost\": CatBoostClassifier(\n",
290
+ " verbose=0,\n",
291
+ " n_estimators=320,\n",
292
+ " max_depth=4\n",
293
+ " )\n",
294
+ "}\n",
295
+ "# Gather importances from the models (from the last fold)\n",
296
+ "importances = {}\n",
297
+ "\n",
298
+ "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
299
+ "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n",
300
+ "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
301
+ "\n",
302
+ "# Create a 1x3 plot\n",
303
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
304
+ "axes = axes.flatten()\n",
305
+ "features = X.columns\n",
306
+ "\n",
307
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
308
+ " # Sort features by importance for a cleaner plot\n",
309
+ " sorted_idx = np.argsort(imp)\n",
310
+ "\n",
311
+ " ax = axes[i]\n",
312
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
313
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
314
+ " ax.set_xlabel(\"Importance Score\")\n",
315
+ "\n",
316
+ "plt.tight_layout()\n",
317
+ "plt.show()"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [
326
+ "# Task 2: Write your code here:\n",
327
+ "# Sort features by importance for a cleaner plot\n",
328
+ " sorted_idx = np.argsort(imp)\n",
329
+ "\n",
330
+ " ax = axes[i]\n",
331
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
332
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
333
+ " ax.set_xlabel(\"Importance Score\")\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 Bonus: Write your code here:"
346
+ ],
347
+ "execution_count": null,
348
+ "outputs": []
349
+ }
350
+ ],
351
+ "metadata": {
352
+ "kernelspec": {
353
+ "display_name": "Python 3",
354
+ "name": "python3"
355
+ },
356
+ "language_info": {
357
+ "name": "python"
358
+ }
359
+ },
360
+ "nbformat": 4,
361
+ "nbformat_minor": 0
362
+ }
submissions_extracted/377/Q1.ipynb ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/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
+ "\n",
22
+ "# Core Libraries\n",
23
+ "import numpy as np\n",
24
+ "import pandas as pd\n",
25
+ "import matplotlib.pyplot as plt\n",
26
+ "import seaborn as sns\n",
27
+ "import warnings\n",
28
+ "warnings.filterwarnings('ignore')\n",
29
+ "import os\n",
30
+ "\n",
31
+ "# Scikit-Learn: Data Preprocessing\n",
32
+ "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold, cross_val_score\n",
33
+ "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n",
34
+ "\n",
35
+ "# Scikit-Learn: Regression Models\n",
36
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
37
+ "from sklearn.tree import DecisionTreeRegressor\n",
38
+ "from sklearn.ensemble import RandomForestRegressor\n",
39
+ "from sklearn.svm import SVR\n",
40
+ "\n",
41
+ "# Scikit-Learn: Classification Models\n",
42
+ "from sklearn.linear_model import LogisticRegression\n",
43
+ "from sklearn.neighbors import KNeighborsClassifier\n",
44
+ "from sklearn.tree import DecisionTreeClassifier\n",
45
+ "from sklearn.ensemble import RandomForestClassifier\n",
46
+ "from sklearn.svm import SVC\n",
47
+ "\n",
48
+ "# Scikit-Learn: Metrics\n",
49
+ "from sklearn.metrics import (\n",
50
+ " mean_absolute_error, mean_squared_error, r2_score,\n",
51
+ " accuracy_score, precision_score, recall_score, f1_score,\n",
52
+ " confusion_matrix, classification_report\n",
53
+ ")\n"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 1: Write your code here:\n",
63
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
64
+ "\n",
65
+ "df = pd.read_csv(csv_path)\n"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 2: Write your code here:\n",
75
+ "df.head()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 3: Write your code here:\n",
85
+ "df.info()"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# Task 4: Write your code here:\n",
95
+ "df.describe()"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# Task 5: Write your code here:\n",
105
+ "\n",
106
+ "def check_target_distribution(df, target_column):\n",
107
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
108
+ "\n",
109
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
110
+ " plt.xlabel(target_column)\n",
111
+ " plt.ylabel(\"Frequency\")\n",
112
+ " plt.grid(False)\n",
113
+ "\n",
114
+ " plt.show()\n",
115
+ "\n",
116
+ "check_target_distribution(df, \"Delivery_Time\")"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# Task 1: Write your code here:\n",
126
+ "df = df.drop(columns=['Order_ID'])\n",
127
+ "df.isnull().sum()"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "df_clean =df.dropna(subset=['Delivery_Time'])\n",
137
+ "df_clean"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# Task 2: Write your code here:\n",
147
+ "def check_missing_values(df):\n",
148
+ " missing_values = df.isnull().sum()\n",
149
+ " print(\"Missing Values per Column:\")\n",
150
+ " print(missing_values[missing_values > 0])\n",
151
+ " if missing_values.any():\n",
152
+ " print(\"\\nHandle Missing Values as needed.\")\n",
153
+ " else:\n",
154
+ " print(\"\\nNo Missing Values Found.\")\n",
155
+ "check_missing_values(df_clean)"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "df_clean.isnull().sum()"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "for col in ['Weather', 'Traffic_Level']:\n",
174
+ " df_clean[col] = df_clean[col].mode()[0]\n",
175
+ "df_clean"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "# Task 3: Write your code here:\n",
194
+ "def check_duplicates(df):\n",
195
+ " duplicates = df.duplicated().sum()\n",
196
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
197
+ " if duplicates > 0:\n",
198
+ " print(\"Dropping Duplicates...\")\n",
199
+ " df.drop_duplicates(inplace=True) # changes in original data\n",
200
+ " print(\"Duplicates Dropped.\")\n",
201
+ " else:\n",
202
+ " print(\"No Duplicate Samples Found.\")\n",
203
+ "\n",
204
+ "check_duplicates(df_clean)\n",
205
+ "\n"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
215
+ "\n",
216
+ "print(\"Categorical Columns:\", list(categorical_cols))"
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "# Task 4: Write your code here:\n",
226
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
227
+ "label_encoders = {}\n",
228
+ "for col in categorical_cols:\n",
229
+ " le = LabelEncoder()\n",
230
+ " df_clean[col] = le.fit_transform(df_clean[col])\n",
231
+ " label_encoders[col] = le\n",
232
+ "\n",
233
+ "# onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
234
+ "# data_onehot_encoded = onehot_encoder.fit_transform(df_clean[categorical_cols]) # Apply fit_transform to the copied\n"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Task 5: Write your code here:\n",
244
+ "features = df_clean.columns.drop(\"Delivery_Time\")\n",
245
+ "scaler = StandardScaler()\n",
246
+ "df_clean[features] = scaler.fit_transform(df_clean[features])\n",
247
+ "df_clean.head()"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "# Task 6: Write your code here:\n",
257
+ "# slightly right skwed so considered balanced"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
267
+ "y = df_clean['Delivery_Time'].astype(float)"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "models = {\n",
277
+ " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
278
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
279
+ "}"
280
+ ],
281
+ "execution_count": null,
282
+ "outputs": []
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "metadata": {},
287
+ "source": [
288
+ "all_results = {}\n",
289
+ "\n",
290
+ "for name in models:\n",
291
+ " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}"
292
+ ],
293
+ "execution_count": null,
294
+ "outputs": []
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "metadata": {},
299
+ "source": [
300
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "metadata": {},
308
+ "source": [
309
+ "# Task 1: Write your code here:\n",
310
+ "\n",
311
+ "n_splits = 5 # K=5 Folds\n",
312
+ "\n",
313
+ "# 5-Fold Cross-Validation, shuffled\n",
314
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
315
+ "\n",
316
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
317
+ "\n",
318
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
319
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
320
+ "\n",
321
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
322
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
323
+ "\n",
324
+ " for model_name, model in models.items():\n",
325
+ " print(f\"Training {model_name}...\")\n",
326
+ "\n",
327
+ " # Train\n",
328
+ " model.fit(X_train, y_train)\n",
329
+ "\n",
330
+ " # Predict\n",
331
+ " y_pred = model.predict(X_test)\n",
332
+ "\n",
333
+ " # Calculate metrics\n",
334
+ " mse = sklearn_mse(y_test, y_pred)\n",
335
+ " rmse = np.sqrt(mse)\n",
336
+ " r2 = r2_score(y_test, y_pred)\n",
337
+ "\n",
338
+ " # Store results\n",
339
+ " all_results[model_name][\"mse\"].append(mse)\n",
340
+ " all_results[model_name][\"rmse\"].append(rmse)\n",
341
+ " all_results[model_name][\"r2\"].append(r2)"
342
+ ],
343
+ "execution_count": null,
344
+ "outputs": []
345
+ },
346
+ {
347
+ "cell_type": "code",
348
+ "metadata": {},
349
+ "source": [
350
+ "for model_name in all_results:\n",
351
+ " print(f\"\\n{model_name}:\")\n",
352
+ " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
353
+ " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
354
+ " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
355
+ ],
356
+ "execution_count": null,
357
+ "outputs": []
358
+ },
359
+ {
360
+ "cell_type": "code",
361
+ "metadata": {},
362
+ "source": [],
363
+ "execution_count": null,
364
+ "outputs": []
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "metadata": {},
369
+ "source": [],
370
+ "execution_count": null,
371
+ "outputs": []
372
+ },
373
+ {
374
+ "cell_type": "code",
375
+ "metadata": {},
376
+ "source": [
377
+ "# Task 2,3,4,5: Write your code here:"
378
+ ],
379
+ "execution_count": null,
380
+ "outputs": []
381
+ },
382
+ {
383
+ "cell_type": "code",
384
+ "metadata": {},
385
+ "source": [
386
+ "# Task 1: Write your code here:"
387
+ ],
388
+ "execution_count": null,
389
+ "outputs": []
390
+ },
391
+ {
392
+ "cell_type": "code",
393
+ "metadata": {},
394
+ "source": [
395
+ "# Task 2: Write your code here:"
396
+ ],
397
+ "execution_count": null,
398
+ "outputs": []
399
+ },
400
+ {
401
+ "cell_type": "code",
402
+ "metadata": {},
403
+ "source": [
404
+ "# Task Bonus: Write your code here:"
405
+ ],
406
+ "execution_count": null,
407
+ "outputs": []
408
+ }
409
+ ],
410
+ "metadata": {
411
+ "kernelspec": {
412
+ "display_name": "Python 3",
413
+ "name": "python3"
414
+ },
415
+ "language_info": {
416
+ "name": "python"
417
+ }
418
+ },
419
+ "nbformat": 4,
420
+ "nbformat_minor": 0
421
+ }
submissions_extracted/377/Q2.ipynb ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import torch.nn.functional as F\n",
29
+ "from torch.optim import Adam, AdamW, SGD\n",
30
+ "from torch.utils.data import DataLoader, TensorDataset\n",
31
+ "\n",
32
+ "import numpy as np\n",
33
+ "import pandas as pd\n",
34
+ "import matplotlib.pyplot as plt\n",
35
+ "\n",
36
+ "from sklearn.model_selection import train_test_split\n",
37
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
38
+ "from sklearn.datasets import load_breast_cancer, load_iris, load_diabetes\n",
39
+ "\n",
40
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
41
+ "print(f\"Device: {device}\")\n",
42
+ "\n",
43
+ "# Load Labels\n",
44
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
45
+ "img_dir = os.path.join(path, \"images\")\n",
46
+ "\n",
47
+ "images = []\n",
48
+ "ages = []\n",
49
+ "\n",
50
+ "# Load Images and Resize\n",
51
+ "print(\"Loading images...\")\n",
52
+ "for index, row in labels_df.iterrows():\n",
53
+ " img_name = row.iloc[0]\n",
54
+ " age = row.iloc[1]\n",
55
+ " img_path = os.path.join(img_dir, img_name)\n",
56
+ "\n",
57
+ " if os.path.exists(img_path):\n",
58
+ " img = Image.open(img_path).convert('RGB')\n",
59
+ " img_array = np.array(img)\n",
60
+ " images.append(img_array)\n",
61
+ " ages.append(age)\n",
62
+ "\n",
63
+ "X = np.array(images)\n",
64
+ "y = np.array(ages)\n",
65
+ "\n",
66
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
67
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
68
+ "\n",
69
+ "# Split Data\n",
70
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
71
+ "\n",
72
+ "print(f\"X_train shape: {X_train.shape}\")\n",
73
+ "print(f\"X_test shape: {X_test.shape}\")\n",
74
+ "print(f\"y_train shape: {y_train.shape}\")\n",
75
+ "print(f\"y_test shape: {y_test.shape}\")"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "\n"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
108
+ "\n",
109
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
110
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
111
+ "y_train = torch.tensor(y_train, dtype=torch.long)\n",
112
+ "y_test = torch.tensor(y_test, dtype=torch.long)\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# 2. Create TensorDataset objects\n",
122
+ "\n",
123
+ "train_dataset = TensorDataset(X_train, y_train)\n",
124
+ "test_dataset = TensorDataset(X_test, y_test)\n",
125
+ "\n"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# 3. Create DataLoaders\n",
135
+ "\n",
136
+ "from torch.utils.data import DataLoader\n",
137
+ "\n",
138
+ "# DataLoader for training data\n",
139
+ "train_loader = DataLoader(\n",
140
+ " train_dataset,\n",
141
+ " batch_size=32,\n",
142
+ " shuffle=True,\n",
143
+ " num_workers=2\n",
144
+ ")\n",
145
+ "# DataLoader for test/validation data\n",
146
+ "test_loader = DataLoader(\n",
147
+ " test_dataset,\n",
148
+ " batch_size=32,\n",
149
+ " shuffle=False,\n",
150
+ " num_workers=2\n",
151
+ ")"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# 4. Print shape of one batch\n",
161
+ "\n",
162
+ "# Get the first batch from the training DataLoader\n",
163
+ "X_batch, y_batch = next(iter(train_loader))\n",
164
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
165
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n",
166
+ "\n",
167
+ "\n"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "images, labels = next(iter(train_loader))\n",
184
+ "\n",
185
+ "# Display the first 6 images in the batch\n",
186
+ "plt.figure(figsize=(8, 4))\n",
187
+ "\n",
188
+ "for i in range(6):\n",
189
+ " plt.subplot(2, 3, i + 1)\n",
190
+ " plt.imshow(images[i].squeeze().view(), cmap='gray')\n",
191
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
192
+ " plt.axis('off')\n",
193
+ "\n",
194
+ "plt.tight_layout()\n",
195
+ "plt.show()\n",
196
+ "\n"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Task 1: Write your model class here:\n",
213
+ "\n",
214
+ "\n",
215
+ "class MulticlassNet(nn.Module):\n",
216
+ " def __init__(self, input_dim, hidden_dim, num_classes):\n",
217
+ " super().__init__()\n",
218
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
219
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
220
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
221
+ " self.layer4 = nn.Linear(hidden_dim, num_classes) # one per class!\n",
222
+ " self.relu = nn.ReLU()\n",
223
+ " # NO softmax! CrossEntropyLoss handles it!\n",
224
+ "\n",
225
+ " def forward(self, x):\n",
226
+ " x = self.relu(self.layer1(x))\n",
227
+ " x = self.relu(self.layer2(x))\n",
228
+ " x = self.relu(self.layer3(x))\n",
229
+ "\n",
230
+ " x = self.layer4(x) # raw logits\n",
231
+ " return x"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task 2: Write your training loop here:\n",
241
+ "INPUT_DIM = X_train.shape[1]\n",
242
+ "HIDDEN_DIM = 64\n",
243
+ "NUM_CLASSES = 10 # for multiclass\n",
244
+ "LEARNING_RATE = 0.001\n",
245
+ "NUM_EPOCHS = 20\n",
246
+ "\n",
247
+ "\n",
248
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device, task):\n",
249
+ " model.train() # TRAINING MODE!\n",
250
+ " running_loss = 0.0\n",
251
+ "\n",
252
+ " for X_batch, y_batch in train_loader:\n",
253
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # flatten image to a vector\n",
254
+ " y_batch = y_batch.to(device)\n",
255
+ "\n",
256
+ "\n",
257
+ " # Forward\n",
258
+ " outputs = model(X_batch)\n",
259
+ " loss = criterion(outputs, y_batch)\n",
260
+ "\n",
261
+ " # Backward - THIS ORDER MATTERS!\n",
262
+ " optimizer.zero_grad() # 1️⃣ Clear gradients\n",
263
+ " loss.backward() # 2️⃣ Compute gradients\n",
264
+ " optimizer.step() # 3️⃣ Update weights\n",
265
+ "\n",
266
+ " running_loss += loss.item()\n",
267
+ "\n",
268
+ " return running_loss / len(train_loader)"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Task 3: Write your validation loop here:\n",
278
+ "\n",
279
+ "def validate(model, criterion, test_loader, device, task):\n",
280
+ " model.eval()\n",
281
+ " running_loss = 0.0\n",
282
+ " correct = 0\n",
283
+ " total = 0\n",
284
+ "\n",
285
+ " with torch.no_grad(): # NO GRADIENTS!\n",
286
+ " for X_batch, y_batch in test_loader:\n",
287
+ " X_batch = X_batch.to(device)\n",
288
+ " y_batch = y_batch.to(device)\n",
289
+ " y_batch_loss = y_batch\n",
290
+ "\n",
291
+ " i_, predicted = torch.max(outputs, dim=1)\n",
292
+ " correct += (predicted == y_batch).sum().item()\n",
293
+ " outputs = model(X_batch)\n",
294
+ " loss = criterion(outputs, y_batch_loss)\n",
295
+ " running_loss += loss.item()\n",
296
+ "\n",
297
+ "\n",
298
+ " avg_loss = running_loss / len(test_loader)\n",
299
+ " accuracy = correct / total if task != \"regression\" else 0\n",
300
+ " return avg_loss, accuracy"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "metadata": {},
308
+ "source": [
309
+ "rain_losses = []\n",
310
+ "val_losses = []\n",
311
+ "val_accs = []\n",
312
+ "\n",
313
+ "print(\"Training started...\")\n",
314
+ "\n",
315
+ "for epoch in range(NUM_EPOCHS):\n",
316
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device, TASK)\n",
317
+ " val_loss, val_acc = validate(model, criterion, test_loader, device, TASK)\n",
318
+ "\n",
319
+ " train_losses.append(train_loss)\n",
320
+ " val_losses.append(val_loss)\n",
321
+ " val_accs.append(val_acc)\n",
322
+ "\n",
323
+ " if (epoch + 1) % 10 == 0:\n",
324
+ " print(f\"Epoch [{epoch+1:3d}/{NUM_EPOCHS}] \"\n",
325
+ " f\"Train Loss: {train_loss:.4f} | \"\n",
326
+ " f\"Val Loss: {val_loss:.4f} | \"\n",
327
+ " f\"Val Acc: {val_acc:.4f}\")\n",
328
+ "\n",
329
+ "print(f\"Done! Final Accuracy: {val_accs[-1]:.4f}\")"
330
+ ],
331
+ "execution_count": null,
332
+ "outputs": []
333
+ },
334
+ {
335
+ "cell_type": "code",
336
+ "metadata": {},
337
+ "source": [
338
+ "# Task 4: Define device, model, loss, optimizer:\n",
339
+ "\n",
340
+ "TASK = \"multiclass\"\n",
341
+ "\n",
342
+ "\n",
343
+ "INPUT_DIM = 3*36*36\n",
344
+ "HIDDEN_DIM = 14\n",
345
+ "OUtPUT_DIM = 1\n",
346
+ "LEARNING_RATE = 0.001\n",
347
+ "NUM_EPOCHS = 20\n",
348
+ "\n",
349
+ "criterion = nn.CrossEntropyLoss()\n",
350
+ "model = MulticlassNet(INPUT_DIM, HIDDEN_DIM, NUM_CLASSES).to(device)\n",
351
+ "optimizer = Adam(model.parameters(), lr=LEARNING_RATE)\n",
352
+ "\n",
353
+ "train_losses = []\n",
354
+ "val_losses = []\n",
355
+ "val_accs = []\n",
356
+ "\n"
357
+ ],
358
+ "execution_count": null,
359
+ "outputs": []
360
+ },
361
+ {
362
+ "cell_type": "code",
363
+ "metadata": {},
364
+ "source": [
365
+ "# Task 5: Start training for 20 epochs:\n",
366
+ "# Run Training\n",
367
+ "train_losses = []\n",
368
+ "val_losses = []\n",
369
+ "\n",
370
+ "print('Starting Training...')\n",
371
+ "for epoch in range(NUM_EPOCHS):\n",
372
+ " # Train one epoch\n",
373
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
374
+ "\n",
375
+ " # Validate\n",
376
+ " val_loss = validate(model, criterion, test_loader, device)\n",
377
+ "\n",
378
+ " train_losses.append(train_loss)\n",
379
+ " val_losses.append(val_loss)\n",
380
+ "\n",
381
+ " if (epoch + 1) % 5 == 0:\n",
382
+ " print(\n",
383
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
384
+ " f'Train Loss: {train_loss:.4f}, '\n",
385
+ " f'Val Loss: {val_loss:.4f}'\n",
386
+ " )\n",
387
+ "\n"
388
+ ],
389
+ "execution_count": null,
390
+ "outputs": []
391
+ },
392
+ {
393
+ "cell_type": "code",
394
+ "metadata": {},
395
+ "source": [],
396
+ "execution_count": null,
397
+ "outputs": []
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "metadata": {},
402
+ "source": [
403
+ "# Task 1: Write your code here:\n",
404
+ "\n",
405
+ "plt.figure(figsize=(12, 4))\n",
406
+ "\n",
407
+ "plt.subplot(1, 2, 1)\n",
408
+ "plt.plot(train_losses, label='Train Loss')\n",
409
+ "plt.plot(val_losses, label='Val Loss')\n",
410
+ "plt.xlabel('Epoch')\n",
411
+ "plt.ylabel('Loss')\n",
412
+ "plt.title('Loss Curves')\n",
413
+ "plt.legend()\n",
414
+ "\n",
415
+ "plt.subplot(1, 2, 2)\n",
416
+ "plt.plot(val_accs, label='Val Accuracy', color='green')\n",
417
+ "plt.xlabel('Epoch')\n",
418
+ "plt.ylabel('Accuracy')\n",
419
+ "plt.title('Validation Accuracy')\n",
420
+ "plt.legend()\n",
421
+ "\n",
422
+ "plt.tight_layout()\n",
423
+ "plt.show()"
424
+ ],
425
+ "execution_count": null,
426
+ "outputs": []
427
+ },
428
+ {
429
+ "cell_type": "code",
430
+ "metadata": {},
431
+ "source": [
432
+ "# Task 2 (Bonus): Write your code here:"
433
+ ],
434
+ "execution_count": null,
435
+ "outputs": []
436
+ }
437
+ ],
438
+ "metadata": {
439
+ "kernelspec": {
440
+ "display_name": "Python 3",
441
+ "name": "python3"
442
+ },
443
+ "language_info": {
444
+ "name": "python"
445
+ }
446
+ },
447
+ "nbformat": 4,
448
+ "nbformat_minor": 0
449
+ }
submissions_extracted/377/Q3.ipynb ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "# WISH I HAD TIME TO SOLVE"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "# Task 2: Write your code here:"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 3: Write your code here:"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 4: Write your code here:"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 1: Write your code here:"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 2: Write your code here:"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# Task 3: Write your code here:"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# Task 4: Write your code here:"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# Task 5: Write your code here:"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 1: Write your code here:"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 2,3,4,5: Write your code here:"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# Task 1: Write your code here:"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "# Task 2: Write your code here:"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task Bonus: Write your code here:"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ }
150
+ ],
151
+ "metadata": {
152
+ "kernelspec": {
153
+ "display_name": "Python 3",
154
+ "name": "python3"
155
+ },
156
+ "language_info": {
157
+ "name": "python"
158
+ }
159
+ },
160
+ "nbformat": 4,
161
+ "nbformat_minor": 0
162
+ }
submissions_extracted/378/Q1.ipynb ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "csv_path = path.join(path, \"Advertising.csv\")\n",
23
+ "df_deliver= pd.read_csv(csv_path)"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 2: Write your code here:\n",
33
+ "df_deliver.head()"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 3: Write your code here:\n",
43
+ "df_deliver.info()"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Task 4: Write your code here:\n",
53
+ "df_deliver.describe()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 5: Write your code here:\n",
63
+ "plt.figure(figsize=(15, 10))\n",
64
+ "plt.hist(df_deliver, bins=50, edgecolor='black')\n",
65
+ "plt.title('price per meals')\n",
66
+ "plt.xlabel('km')\n",
67
+ "plt.ylabel('Frequency')\n",
68
+ "plt.show()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 1: Write your code here:\n",
78
+ "df_deliver = df_deliver.dropna(subset='Order_ID')"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# Task 2: Write your code here:\n",
88
+ "import pandas as pd\n",
89
+ "import numpy as np\n",
90
+ "# Create sample data with missing values\n",
91
+ "df = pd.DataFrame({})\n",
92
+ "print(\"Original Data:\")\n",
93
+ "print(df)\n",
94
+ "print(\"\\nMissing values:\")\n",
95
+ "print(df.isnull().sum())\n"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# Task 3: Write your code here:"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 4: Write your code here:\n",
114
+ "from sklearn.preprocessing import OneHotEncoder\n",
115
+ "colors = [['burger'], ['pizza'], ['coffee'], ['icecream']]\n",
116
+ "encoder = OneHotEncoder(sparse_output=False)\n",
117
+ "encoded = encoder.fit_transform(colors)\n",
118
+ "print(\"Original:\", colors)\n",
119
+ "print(\"Encoded:\\n\", encoded)"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 5: Write your code here:\n",
129
+ "import numpy as np\n",
130
+ "from sklearn.preprocessing import StandardScaler\n",
131
+ "data = np.array([[1, 150, 40],\n",
132
+ " [2, 100, 60],\n",
133
+ " [3, 300, 80]])\n",
134
+ "\n",
135
+ "scaler = StandardScaler()\n",
136
+ "scaler.fit(data)\n",
137
+ "scaled = scaler.fit_transform(data)"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# Task 6: Write your code here:"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# Task 1: Write your code here:\n",
156
+ "import numpy as np\n",
157
+ "\n",
158
+ "from sklearn.model_selection import train_test_split\n",
159
+ "X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])\n",
160
+ "y = np.array([0, 1, 0, 1, 0])\n",
161
+ "# split\n",
162
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
163
+ "print(f\"\\nX_train:\\n{X_train}\")\n",
164
+ "print(f\"\\nX_test:\\n{X_test}\")"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 2,3,4,5: Write your code here:\n",
174
+ "#fold\n",
175
+ "from sklearn.model_selection import train_test_split\n",
176
+ "X, y = X_clf.copy(), y_clf.copy()\n",
177
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
178
+ "print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
179
+ "for fold, (train_idx, test_idx) in kfold.split(kf.split(X), start=1):\n",
180
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
181
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
182
+ " # print shapes\n",
183
+ " print(f\"Fold {fold}\")\n",
184
+ " print(\" X_train shape:\", X_train.shape)\n",
185
+ " print(\" X_test shape :\", X_test.shape)\n",
186
+ " print(\" y_train shape:\", y_train.shape)\n",
187
+ " print(\" y_test shape :\", y_test.shape)\n",
188
+ " print(\"-\" * 25)\n",
189
+ "#using randomforest\n",
190
+ "model = RandomForestClassifier(n_estimators=100, random_state=42)\n",
191
+ "model.fit(scaled, y_train)\n",
192
+ "print(\"Random Forest:\")\n",
193
+ "#evaluate absulote error\n",
194
+ "mae = mean_absolute_error(y_true, y_pred)\n",
195
+ "print(f\"MAE: {mae:.2f}\")\n",
196
+ "\n",
197
+ "#average\n",
198
+ "average_losses = np.mean(lr_losses, axis=0)\n",
199
+ "plt.figure(figsize=(10, 6))\n",
200
+ "plt.plot(average_losses, label='Average Loss')\n",
201
+ "plt.xlabel('Iteration')\n",
202
+ "plt.ylabel('MAE Loss')\n",
203
+ "plt.grid(True, alpha=0.3)\n",
204
+ "plt.show()\n"
205
+ ],
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "metadata": {},
212
+ "source": [
213
+ "# Task 1: Write your code here:"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 2: Write your code here:"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "# Task Bonus: Write your code here:"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ }
236
+ ],
237
+ "metadata": {
238
+ "kernelspec": {
239
+ "display_name": "Python 3",
240
+ "name": "python3"
241
+ },
242
+ "language_info": {
243
+ "name": "python"
244
+ }
245
+ },
246
+ "nbformat": 4,
247
+ "nbformat_minor": 0
248
+ }
submissions_extracted/378/Q2.ipynb ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
70
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
71
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
72
+ "y_test = torch.tensor(y_test, dtype=torch.float32)"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# 2. Create TensorDataset objects\n",
82
+ "import torch\n",
83
+ "train_dataset\n",
84
+ "# Create tensors\n",
85
+ "X = torch.tensor([1.0, 2.0, 3.0])\n",
86
+ "Y = torch.randn(3)\n",
87
+ "print(\"X:\", X)\n",
88
+ "print(\"Y:\", Y)"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# 3. Create DataLoaders\n",
98
+ "# for training data\n",
99
+ "train_loader = DataLoader(\n",
100
+ " train_dataset,\n",
101
+ " batch_size=32,\n",
102
+ " shuffle=True)\n",
103
+ "# for test data\n",
104
+ "test_loader = DataLoader(\n",
105
+ " test_dataset,\n",
106
+ " batch_size=32,\n",
107
+ " shuffle=False)"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# 4. Print shape of one batch\n",
117
+ "X_batch= next(iter(train_loader))\n",
118
+ "print(f\"Training batch input shape: {X_batch.shape}\")"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# 5. Display sample images\n",
128
+ "\n"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 1: Write your model class here:\n",
138
+ "import torch.nn as nn\n",
139
+ "class NN4Layer(nn.Module):\n",
140
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
141
+ " super(NN4Layer, self).__init__()\n",
142
+ " # First layer\n",
143
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
144
+ " # Second layer\n",
145
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
146
+ " # Third layer\n",
147
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
148
+ " # Output layer\n",
149
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
150
+ " # ReLU activation 4 non-linearity\n",
151
+ " self.relu = nn.ReLU()\n",
152
+ " # Defines how input data flows through the network\n",
153
+ " def forward(self, x):\n",
154
+ " # First hidden layer\n",
155
+ " a1 = self.relu(self.layer1(x))\n",
156
+ " # Second hidden layer\n",
157
+ " a2 = self.relu(self.layer2(a1))\n",
158
+ " # Third hidden layer\n",
159
+ " a3 = self.relu(self.layer3(a2))\n",
160
+ " # Output layer (raw scores / logits)\n",
161
+ " output = self.layer4(a3)\n",
162
+ " return output"
163
+ ],
164
+ "execution_count": null,
165
+ "outputs": []
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "metadata": {},
170
+ "source": [
171
+ "# Task 2: Write your training loop here:\n",
172
+ "def train_one_epoch(model, optimizer, criterion, train_loader):\n",
173
+ " # Set the model to training mode\n",
174
+ " model.train()\n",
175
+ " running_loss = 0.0\n",
176
+ " for X_batch, y_batch in train_loader:\n",
177
+ " # Forward pass (the outputs)\n",
178
+ " outputs = model(X_batch)\n",
179
+ " loss = criterion(outputs, y_batch)\n",
180
+ " # Backward pasS and optimization\n",
181
+ " optimizer.zero_grad()\n",
182
+ " loss.backward()\n",
183
+ " optimizer.step()\n",
184
+ " running_loss += loss.item()"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "# Task 3: Write your validation loop here:\n",
194
+ "def validate(model, criterion, test_loader):\n",
195
+ "#evaluate the model\n",
196
+ " model.eval()\n",
197
+ " running_loss = 0.0\n",
198
+ " correct = 0\n",
199
+ " total = 0\n",
200
+ " with torch.no_grad():\n",
201
+ " # Forward pass\n",
202
+ " outputs = model(X_batch)\n",
203
+ " loss = criterion(outputs, y_batch)\n",
204
+ " running_loss += loss.item()\n",
205
+ " # Softmax to get probabilities\n",
206
+ " probabilities = F.softmax(outputs, dim=1)\n",
207
+ " # classes w/ highest probabilities\n",
208
+ " predicted = torch.argmax(probabilities, dim=1)\n",
209
+ " # Accuracy calculation\n",
210
+ " correct += (predicted == y_batch).sum().item()\n",
211
+ " total += y_batch.size(0)\n",
212
+ " avg_loss = running_loss / len(test_loader)\n",
213
+ " accuracy = correct / total\n",
214
+ " return avg_loss, accuracy"
215
+ ],
216
+ "execution_count": null,
217
+ "outputs": []
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "metadata": {},
222
+ "source": [
223
+ "# Task 4: Define device, model, loss, optimizer:\n",
224
+ "import torch\n",
225
+ "import torch.nn as nn\n",
226
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
227
+ "x = torch.randn(4, 3)\n",
228
+ "y = linear(x)\n",
229
+ "print(\"Input shape:\", x.shape)\n",
230
+ "print(\"Output shape:\", y.shape)\n",
231
+ "#loss\n",
232
+ "criterion = nn.CrossEntropyLoss()\n",
233
+ "#device\n",
234
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
235
+ "print(f\"Using device: {device}\")\n",
236
+ "\n",
237
+ "#optimizer\n",
238
+ "optimizer = AdamW(model.parameters(), learning_rate)"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [
247
+ "# Task 5: Start training for 20 epochs:\n",
248
+ "num_epochs = 20\n",
249
+ "learning_rate = 0.001\n",
250
+ "input_dim = X_train.shape[1]\n",
251
+ "hidden_dim = 10\n",
252
+ "model =NN2Layer(input_dim, hidden_dim).to(device)\n",
253
+ "criterion = nn.BCELoss()\n",
254
+ "optimizer = AdamW(model.parameters(), lr=learning_rate)\n",
255
+ "# Run Training\n",
256
+ "train_losses = []\n",
257
+ "val_losses = []\n",
258
+ "val_accuracies = []\n",
259
+ "print('Starting Training...')\n",
260
+ "for epoch in range(num_epochs):\n",
261
+ " # Train one epoch\n",
262
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
263
+ " # Validate\n",
264
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
265
+ " train_losses.append(train_loss)\n",
266
+ " val_losses.append(val_loss)\n",
267
+ " val_accuracies.append(val_accuracy)\n",
268
+ " if (epoch + 1) % 5 == 0:\n",
269
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
270
+ "print('Done!')"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "metadata": {},
278
+ "source": [
279
+ "# Task 1: Write your code here:\n",
280
+ "plt.figure(figsize=(7, 5))\n",
281
+ "plt.plot(train_losses, label='T Loss')\n",
282
+ "plt.plot(val_losses, label='Val Loss')\n",
283
+ "plt.title('Loss over Epochs')\n",
284
+ "plt.xlabel('Epoch')\n",
285
+ "plt.ylabel('Loss')\n",
286
+ "plt.legend()\n",
287
+ "plt.tight_layout()\n",
288
+ "plt.show()"
289
+ ],
290
+ "execution_count": null,
291
+ "outputs": []
292
+ },
293
+ {
294
+ "cell_type": "code",
295
+ "metadata": {},
296
+ "source": [
297
+ "# Task 2 (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/378/Q3.ipynb ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "csv_path = path.join(path, \"updated_ai_dataset.csv\")\n",
29
+ "df = pd.read_csv(csv_path)"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "# Task 2: Write your code here:\n",
39
+ "df.head()"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "# Task 3: Write your code here:\n",
49
+ "df.info()"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 4: Write your code here:\n",
59
+ "df.describe()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 1: Write your code here:"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 2: Write your code here:"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 3: Write your code here:"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 4: Write your code here:"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# Task 5: Write your code here:"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 1: Write your code here:"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# Task 2,3,4,5: Write your code here:"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# Task 1: Write your code here:"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 2: Write your code here:"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "# Task Bonus: Write your code here:"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ }
154
+ ],
155
+ "metadata": {
156
+ "kernelspec": {
157
+ "display_name": "Python 3",
158
+ "name": "python3"
159
+ },
160
+ "language_info": {
161
+ "name": "python"
162
+ }
163
+ },
164
+ "nbformat": 4,
165
+ "nbformat_minor": 0
166
+ }
submissions_extracted/379/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
+ "import numpy as np\n",
10
+ "import os\n",
11
+ "import pandas as pd\n",
12
+ "import matplotlib.pyplot as plt\n",
13
+ "\n",
14
+ "\n",
15
+ "# Download latest version\n",
16
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
17
+ "\n",
18
+ "print(\"Path to dataset files:\", path)"
19
+ ],
20
+ "execution_count": null,
21
+ "outputs": []
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "# Task 1: Write your code here:\n",
28
+ "Q1_data = os.path.join(path, \"Q1_data.csv\")\n",
29
+ "df = pd.read_csv(Q1_data)"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "# Task 2: Write your code here:\n",
39
+ "df.head()"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "# Task 3: Write your code here:\n",
49
+ "df.info()"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 4: Write your code here:\n",
59
+ "df.describe()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 5: Write your code here:\n",
69
+ "def check_target_distribution(df, Delivery_Time):\n",
70
+ "\n",
71
+ " df[Delivery_Time].hist(bins=30, edgecolor='black')\n",
72
+ "\n",
73
+ " plt.title(f\"Target Distribution ({Delivery_Time})\")\n",
74
+ "\n",
75
+ " plt.xlabel(Delivery_Time)\n",
76
+ "\n",
77
+ "\n",
78
+ " plt.ylabel(\"Frequency\")\n",
79
+ "\n",
80
+ "\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(columns=\"Order_ID\", axis=1)"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "def check_missing_values(df):\n",
105
+ "\n",
106
+ " missing_values = df.isnull().sum()\n",
107
+ "\n",
108
+ " print(\"Missing Values per Column:\")\n",
109
+ " # Label for clarity\n",
110
+ "\n",
111
+ " print(missing_values[missing_values > 0])\n",
112
+ "\n",
113
+ " if missing_values.any():\n",
114
+ "\n",
115
+ " print(\"\\nHandle Missing Values as needed.\")\n",
116
+ " else:\n",
117
+ " print(\"\\nNo Missing Values Found.\")\n",
118
+ "\n",
119
+ "check_missing_values(df)\n",
120
+ "\n",
121
+ "# Define stat columns\n",
122
+ "stat_cols = ['Distance_km'\t,'Weather'\t,'Traffic_Level'\t,'Time_of_Day'\t,'Vehicle_Type'\t,'Preparation_Time_min'\t,'Courier_Experience_yrs','Delivery_Time']\n",
123
+ "\n",
124
+ "# Drop rows with missing stat values\n",
125
+ "df_clean = df.dropna(subset=stat_cols).copy()\n",
126
+ "print(f\"Shape after cleaning: {df_clean.shape}\")"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "# Task 3: Write your code here:\n",
136
+ "def check_duplicates(df):\n",
137
+ "\n",
138
+ " duplicates = df.duplicated().sum()\n",
139
+ "\n",
140
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
141
+ "\n",
142
+ " if duplicates > 0:\n",
143
+ " print(\"Dropping Duplicates...\")\n",
144
+ "\n",
145
+ " df.drop_duplicates(inplace=True)\n",
146
+ "\n",
147
+ " print(\"Duplicates Dropped.\")\n",
148
+ " else:\n",
149
+ " print(\"No Duplicate Samples Found.\")\n",
150
+ "\n",
151
+ "\n",
152
+ "\n",
153
+ "check_duplicates(df)"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 4: Write your code here:\n",
163
+ "from sklearn.preprocessing import LabelEncoder\n",
164
+ "\n",
165
+ "categorical_cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n",
166
+ "for col in categorical_cols:\n",
167
+ " le = LabelEncoder()\n",
168
+ " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
169
+ "\n",
170
+ "df_clean.head()"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 5: Write your code here:\n",
180
+ "df = df_clean\n",
181
+ "from sklearn.preprocessing import StandardScaler\n",
182
+ "\n",
183
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n",
184
+ "\n",
185
+ "scaler = StandardScaler()\n",
186
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
187
+ "df.head()\n"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# Task 6: Write your code here:"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task 1: Write your code here:\n",
206
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
207
+ "y = df['Delivery_Time'].astype(float)"
208
+ ],
209
+ "execution_count": null,
210
+ "outputs": []
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "metadata": {},
215
+ "source": [
216
+ "from sklearn.model_selection import KFold\n",
217
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
218
+ "# Task 2,3,4,5: Write your code here:\n",
219
+ "n_splits = 5 # K=5 Folds\n",
220
+ "\n",
221
+ "# 5-Fold Cross-Validation, shuffled\n",
222
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
223
+ "\n",
224
+ "# Storage for linear regression results for each fold\n",
225
+ "lr_losses = []\n",
226
+ "lr_mse = []\n",
227
+ "lr_rmse = []\n",
228
+ "lr_r2 = []\n",
229
+ "\n",
230
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
231
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
232
+ "\n",
233
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
234
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
235
+ "\n",
236
+ "from sklearn.ensemble import RandomForestRegressor\n",
237
+ "\n"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Task 1: Write your code here:"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "source": [
255
+ "# Task 2: Write your code here:"
256
+ ],
257
+ "execution_count": null,
258
+ "outputs": []
259
+ },
260
+ {
261
+ "cell_type": "code",
262
+ "metadata": {},
263
+ "source": [
264
+ "# Task Bonus: Write your code here:"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ }
269
+ ],
270
+ "metadata": {
271
+ "kernelspec": {
272
+ "display_name": "Python 3",
273
+ "name": "python3"
274
+ },
275
+ "language_info": {
276
+ "name": "python"
277
+ }
278
+ },
279
+ "nbformat": 4,
280
+ "nbformat_minor": 0
281
+ }
submissions_extracted/379/Q2.ipynb ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "from torchvision.transforms.functional import to_tensor\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your training loop here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 3: Write your validation loop here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Define device, model, loss, optimizer:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Start training for 20 epochs:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2 (Bonus): Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ }
180
+ ],
181
+ "metadata": {
182
+ "kernelspec": {
183
+ "display_name": "Python 3",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "name": "python"
188
+ }
189
+ },
190
+ "nbformat": 4,
191
+ "nbformat_minor": 0
192
+ }
submissions_extracted/379/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/38/Q1.ipynb ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import os\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
13
+ "\n",
14
+ "print(\"Path to dataset files:\", path)"
15
+ ],
16
+ "execution_count": null,
17
+ "outputs": []
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "metadata": {},
22
+ "source": [
23
+ "# Task 1: Write your code here:\n",
24
+ "csv = os.path.join(path, \"Q1_data.csv\")\n",
25
+ "df = pd.read_csv(csv)"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "# Task 2: Write your code here:\n",
35
+ "df.head()"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 3: Write your code here:\n",
45
+ "df.info()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 4: Write your code here:\n",
55
+ "df.describe()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 5: Write your code here:\n",
65
+ "import matplotlib.pyplot as plt\n",
66
+ "\n",
67
+ "plt.figure(figsize=(10, 5))\n",
68
+ "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
69
+ "plt.title('Delivery Time')\n",
70
+ "plt.xlabel('Preparation Time')\n",
71
+ "plt.ylabel('Distance')\n",
72
+ "plt.show()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# Task 1: Write your code here:\n",
82
+ "df_clean = df.drop(\"Order_ID\", axis=1)\n",
83
+ "df_clean"
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
+ "df_clean = df_clean.dropna()\n",
94
+ "df_clean"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 3: Write your code here:\n",
104
+ "print(\"Checking for duplicate rows\")\n",
105
+ "duplicate_rows = df_clean.duplicated().sum()\n",
106
+ "if duplicate_rows > 0:\n",
107
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them\")\n",
108
+ " df_clean.drop_duplicates(inplace=True)\n",
109
+ " print(\"Duplicate rows removed.\")\n",
110
+ "else:\n",
111
+ " print(\"No duplicate rows found.\")"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "# Task 4: Write your code here:\n",
121
+ "from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder\n",
122
+ "from sklearn.model_selection import train_test_split, KFold\n",
123
+ "\n",
124
+ "X = df.drop('Delivery_Time', axis=1)\n",
125
+ "y = df[\"Delivery_Time\"]\n",
126
+ "\n",
127
+ "label_encoder = LabelEncoder()\n",
128
+ "y_encoded = label_encoder.fit_transform(y)\n",
129
+ "\n",
130
+ "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n",
131
+ "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n",
132
+ "X_encoded"
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
+ "scaler = StandardScaler()\n",
143
+ "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n",
144
+ "\n",
145
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
146
+ "X_test_scaled = scaler.transform(X_test)\n",
147
+ "\n",
148
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
149
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "# Task 6: Write your code here:"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "metadata": {},
166
+ "source": [
167
+ "# Task 1: Write your code here:\n",
168
+ "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 2,3,4,5: Write your code here:\n",
178
+ "from sklearn.ensemble import RandomForestRegressor\n",
179
+ "\n",
180
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
181
+ "model.fit(X_train_scaled, y_train)\n",
182
+ "print(\"Model trained!\")"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "# Task 1: Write your code here:\n",
192
+ "importance = pd.DataFrame({\n",
193
+ " 'feature': \"Delevery_Time\",\n",
194
+ " 'importance': model.feature_importances_\n",
195
+ "}).sort_values('importance', ascending=False)\n",
196
+ "\n",
197
+ "plt.figure(figsize=(10, 6))\n",
198
+ "plt.barh(importance['feature'], importance['importance'], color='blue')\n",
199
+ "plt.xlabel('Importance')\n",
200
+ "plt.title('Feature Importance')\n",
201
+ "plt.gca().invert_yaxis()\n",
202
+ "plt.show()"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# Task 2: Write your code here:"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "# Task Bonus: Write your code here:"
221
+ ],
222
+ "execution_count": null,
223
+ "outputs": []
224
+ }
225
+ ],
226
+ "metadata": {
227
+ "kernelspec": {
228
+ "display_name": "Python 3",
229
+ "name": "python3"
230
+ },
231
+ "language_info": {
232
+ "name": "python"
233
+ }
234
+ },
235
+ "nbformat": 4,
236
+ "nbformat_minor": 0
237
+ }
submissions_extracted/38/Q2.ipynb ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your training loop here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 3: Write your validation loop here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Define device, model, loss, optimizer:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Start training for 20 epochs:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2 (Bonus): Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ }
180
+ ],
181
+ "metadata": {
182
+ "kernelspec": {
183
+ "display_name": "Python 3",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "name": "python"
188
+ }
189
+ },
190
+ "nbformat": 4,
191
+ "nbformat_minor": 0
192
+ }
submissions_extracted/38/Q3.ipynb ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "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
+ "import os\n",
27
+ "import pandas as pd\n",
28
+ "\n",
29
+ "csv = os.path.join(path, \"Q3_data.csv\")\n",
30
+ "df = pd.read_csv(csv)\n",
31
+ "df"
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
+ "df_clean = df.dropna()\n",
72
+ "df_clean"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# Task 2: Write your code here:\n",
82
+ "print(\"Checking for duplicate rows\")\n",
83
+ "duplicate_rows = df_clean.duplicated().sum()\n",
84
+ "if duplicate_rows > 0:\n",
85
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them\")\n",
86
+ " df_clean.drop_duplicates(inplace=True)\n",
87
+ " print(\"Duplicate rows removed.\")\n",
88
+ "else:\n",
89
+ " print(\"No duplicate rows found.\")"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 3: Write your code here:\n",
99
+ "from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder\n",
100
+ "from sklearn.model_selection import train_test_split, KFold\n",
101
+ "\n",
102
+ "X = df.drop('Target', axis=1)\n",
103
+ "y = df[\"Target\"]\n",
104
+ "\n",
105
+ "label_encoder = LabelEncoder()\n",
106
+ "y_encoded = label_encoder.fit_transform(y)\n",
107
+ "\n",
108
+ "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n",
109
+ "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n",
110
+ "X_encoded"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "# Task 4: Write your code here:\n",
120
+ "from sklearn.preprocessing import StandardScaler\n",
121
+ "from sklearn.model_selection import train_test_split\n",
122
+ "\n",
123
+ "scaler = StandardScaler()\n",
124
+ "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n",
125
+ "\n",
126
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
127
+ "X_test_scaled = scaler.transform(X_test)\n",
128
+ "\n",
129
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
130
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 5: Write your code here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 1: Write your code here:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 2,3,4,5: Write your code here:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2: Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task Bonus: Write your code here:"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ }
189
+ ],
190
+ "metadata": {
191
+ "kernelspec": {
192
+ "display_name": "Python 3",
193
+ "name": "python3"
194
+ },
195
+ "language_info": {
196
+ "name": "python"
197
+ }
198
+ },
199
+ "nbformat": 4,
200
+ "nbformat_minor": 0
201
+ }
submissions_extracted/380/Q1.ipynb ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "from sklearn.model_selection import train_test_split, KFold\n",
13
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
14
+ "from sklearn.ensemble import RandomForestRegressor\n",
15
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
16
+ "import warnings\n",
17
+ "warnings.filterwarnings('ignore')"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "import kagglehub\n",
27
+ "\n",
28
+ "# Download latest version\n",
29
+ "path =kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
30
+ "\n",
31
+ "print(\"Path to dataset files:\", path)"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 1: =\n",
41
+ "delivery = os.path.join(path, 'Q1_data.csv')\n",
42
+ "delivry = os.path.join(path, 'Q1_data.csv')\n",
43
+ "df = pd.read_csv(delivery)\n",
44
+ "print(f\"Dataset shape: {df.shape}\")\n",
45
+ "df.head()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 2:\n",
55
+ "df.info()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 3:\n",
65
+ "df.describe()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 4:\n",
75
+ "plt.figure(figsize=(10, 5))\n",
76
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
77
+ "plt.show()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 5: Write your code here:"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 1:\n",
96
+ "df.drop(columns=['Order_ID'])\n",
97
+ "df_clean = df[cols].copy()"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 2:\n"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 3:\n",
116
+ "for col in ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day'], df_clean[col] = df_clean[col].fillna('unknown')"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# Task 4: Write your code here:"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# Task 5: Write your code here:"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# Task 6: Write your code here:"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "# Task 1: Write your code here:"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 2,3,4,5: Write your code here:"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 1: Write your code here:"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 2: Write your code here:"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task Bonus: Write your code here:"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ }
193
+ ],
194
+ "metadata": {
195
+ "kernelspec": {
196
+ "display_name": "Python 3",
197
+ "name": "python3"
198
+ },
199
+ "language_info": {
200
+ "name": "python"
201
+ }
202
+ },
203
+ "nbformat": 4,
204
+ "nbformat_minor": 0
205
+ }
submissions_extracted/380/Q2.ipynb ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your training loop here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 3: Write your validation loop here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Define device, model, loss, optimizer:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Start training for 20 epochs:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2 (Bonus): Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ }
180
+ ],
181
+ "metadata": {
182
+ "kernelspec": {
183
+ "display_name": "Python 3",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "name": "python"
188
+ }
189
+ },
190
+ "nbformat": 4,
191
+ "nbformat_minor": 0
192
+ }
submissions_extracted/380/Q3.ipynb ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "from sklearn.model_selection import train_test_split, KFold\n",
13
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
14
+ "from sklearn.ensemble import RandomForestRegressor\n",
15
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
16
+ "import warnings\n",
17
+ "warnings.filterwarnings('ignore')"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "import kagglehub\n",
27
+ "\n",
28
+ "\n",
29
+ "\n",
30
+ "# Download latest version\n",
31
+ "\n",
32
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
33
+ "\n",
34
+ "\n",
35
+ "\n",
36
+ "print(\"Path to dataset files:\", path)"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "delivery = os.path.join(path, 'Q3_data.csv')\n",
46
+ "delivry = os.path.join(path, 'Q3_data.csv')\n",
47
+ "df = pd.read_csv(delivery)\n",
48
+ "print(f\"Dataset shape: {df.shape}\")\n",
49
+ "df.head()"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "df.head()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
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:"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# Task 1: Write your code here:"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# Task 2: Write your code here:"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 3: Write your code here:"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 4: Write your code here:"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 5: Write your code here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 1: Write your code here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 2,3,4,5: Write your code here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 1: Write your code here:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 2: Write your code here:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task Bonus: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ }
171
+ ],
172
+ "metadata": {
173
+ "kernelspec": {
174
+ "display_name": "Python 3",
175
+ "name": "python3"
176
+ },
177
+ "language_info": {
178
+ "name": "python"
179
+ }
180
+ },
181
+ "nbformat": 4,
182
+ "nbformat_minor": 0
183
+ }
submissions_extracted/381/Q1.ipynb ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import os\n",
23
+ "import pandas as pd\n",
24
+ "# Load the dataset\n",
25
+ "data_path = os.path.join(path, 'Q1_data.csv')\n",
26
+ "df_data = pd.read_csv(data_path)"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "# Task 2: Write your code here:\n",
36
+ "print(f\"Dataset shape: {df_data.shape}\")\n",
37
+ "df_data.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_data.info()\n"
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_data.describe()\n"
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
+ "#Plot the target distribution (delivery_time)\n",
68
+ "import matplotlib.pyplot as plt\n",
69
+ "\n",
70
+ "plt.figure(figsize=(10, 5))\n",
71
+ "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
72
+ "plt.title('Distribution Delivery_Time ')\n",
73
+ "plt.xlabel('Delivery_Time')\n",
74
+ "plt.ylabel('Frequency')\n",
75
+ "plt.show()\n",
76
+ "\n"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# Task 1: Write your code here:\n",
86
+ "\n",
87
+ "df_data = df_data.drop(columns=\"Order_ID\", axis=1)\n"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# Task 2: Write your code here:\n",
97
+ "# Analyze missing values\n",
98
+ "missing_percentage = (df_data.isnull().sum() / len(df_data)) * 100\n",
99
+ "missing_data = pd.DataFrame({\n",
100
+ " 'Column': missing_percentage.index,\n",
101
+ " 'Missing_Percentage': missing_percentage.values\n",
102
+ "})\n",
103
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
104
+ "\n",
105
+ "print(\"Missing Data Analysis:\")\n",
106
+ "missing_data.head(10)\n"
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
+ "cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n",
117
+ "df_clean = df_data[cols].copy()\n",
118
+ "print(f\"Before: {df_clean.shape}\")\n",
119
+ "df_clean = df_clean.dropna(subset=['Delivery_Time','Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs'])\n",
120
+ "print(f\"After dropping missing values: {df_clean.shape}\")\n",
121
+ "\n",
122
+ "df_clean.info()\n"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "from sklearn.model_selection import train_test_split, KFold\n",
132
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 4: Write your code here:\n"
142
+ ],
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
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 6: Write your code here:"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your code here:\n"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 2,3,4,5: Write your code here:"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task 1: Write your code here:"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "metadata": {},
194
+ "source": [
195
+ "# Task 2: Write your code here:"
196
+ ],
197
+ "execution_count": null,
198
+ "outputs": []
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "metadata": {},
203
+ "source": [
204
+ "# Task Bonus: Write your code here:"
205
+ ],
206
+ "execution_count": null,
207
+ "outputs": []
208
+ }
209
+ ],
210
+ "metadata": {
211
+ "kernelspec": {
212
+ "display_name": "Python 3",
213
+ "name": "python3"
214
+ },
215
+ "language_info": {
216
+ "name": "python"
217
+ }
218
+ },
219
+ "nbformat": 4,
220
+ "nbformat_minor": 0
221
+ }
submissions_extracted/381/Q2.ipynb ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "from sklearn.datasets import load_breast_cancer\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
+ "# load data\n",
77
+ "data = load_breast_cancer()\n",
78
+ "X = data.data\n",
79
+ "y = data.target\n",
80
+ "\n",
81
+ "# Split the dataset into training and testing sets\n",
82
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# 2. Create TensorDataset objects\n",
92
+ "\n",
93
+ "# Standardize the data\n",
94
+ "scaler = StandardScaler()\n",
95
+ "X_train = scaler.fit_transform(X_train)\n",
96
+ "X_test = scaler.transform(X_test)\n",
97
+ "\n",
98
+ "# transform to tensors\n",
99
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
100
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
101
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
102
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
103
+ "\n",
104
+ "\n",
105
+ "# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
106
+ "# Each item in the dataset is returned as (X[i], y[i])\n",
107
+ "train_dataset = TensorDataset(X_train, y_train)\n",
108
+ "test_dataset = TensorDataset(X_test, y_test)\n",
109
+ "\n",
110
+ "# Access a single sample from the dataset\n",
111
+ "# This helps verify the shape of one data sample\n",
112
+ "first_sample, _ = train_dataset[0]\n",
113
+ "print(f\"Shape of one sample: {first_sample.shape}\")\n"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# 3. Create DataLoaders\n",
123
+ "\n",
124
+ "from torch.utils.data import DataLoader\n",
125
+ "\n",
126
+ "# DataLoader for training data\n",
127
+ "train_loader = DataLoader(\n",
128
+ " train_dataset,\n",
129
+ " batch_size=32,\n",
130
+ " shuffle=True,\n",
131
+ " num_workers=2\n",
132
+ ")\n",
133
+ "# DataLoader for test/validation data\n",
134
+ "test_loader = DataLoader(\n",
135
+ " test_dataset,\n",
136
+ " batch_size=32,\n",
137
+ " shuffle=False,\n",
138
+ " num_workers=2\n",
139
+ ")\n",
140
+ "\n"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "# 4. Print shape of one batch\n",
150
+ "\n",
151
+ "# Get the first batch from the training DataLoader\n",
152
+ "X_batch, y_batch = next(iter(train_loader))\n",
153
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
154
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# 5. Display sample images\n",
164
+ "\n"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 1: Write your model class here:\n",
174
+ "import torch.nn as nn\n",
175
+ "class NN4Layer(nn.Module):\n",
176
+ "\n",
177
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
178
+ " super(NN4Layer, self).__init__()\n",
179
+ "\n",
180
+ " # First linear layer: input features -> hidden layer\n",
181
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
182
+ "\n",
183
+ " # Second linear layer: hidden layer -> hidden layer\n",
184
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
185
+ "\n",
186
+ " # Output layer: hidden layer -> number of classes (logits)\n",
187
+ " self.layer3 = nn.Linear(hidden_dim, output_dim)\n",
188
+ "\n",
189
+ " self.layer4 = nn.linear(hidden_dim, output_dim)\n",
190
+ "\n",
191
+ " # ReLU activation for non-linearity\n",
192
+ " self.relu = nn.ReLU()\n",
193
+ "\n",
194
+ " # Defines how input data flows through the network\n",
195
+ " def forward(self, x):\n",
196
+ " # First hidden layer\n",
197
+ " z1 = self.layer1(x)\n",
198
+ " a1 = self.relu(z1)\n",
199
+ "\n",
200
+ " # Second hidden layer\n",
201
+ " z2 = self.layer2(a1)\n",
202
+ " a2 = self.relu(z2)\n",
203
+ "\n",
204
+ " z3 = self.layer3(a2)\n",
205
+ " a3 = self.relu(z3)\n",
206
+ "\n",
207
+ " # Output layer (raw scores / logits)\n",
208
+ " output = self.layer4(a3) # there is something missing here, remember? :)\n",
209
+ "\n",
210
+ " return output\n"
211
+ ],
212
+ "execution_count": null,
213
+ "outputs": []
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "metadata": {},
218
+ "source": [
219
+ "# Task 2: Write your training loop here:\n",
220
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
221
+ " # Set the model to training mode\n",
222
+ " model.train()\n",
223
+ "\n",
224
+ " running_loss = 0.0\n",
225
+ "\n",
226
+ " for X_batch, y_batch in train_loader:\n",
227
+ " # Move batch to the selected device\n",
228
+ " X_batch = X_batch.to(device)\n",
229
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
230
+ "\n",
231
+ " # Forward pass\n",
232
+ " outputs = model(X_batch)\n",
233
+ " loss = criterion(outputs, y_batch)\n",
234
+ "\n",
235
+ " # Backward pass & optimization\n",
236
+ " optimizer.zero_grad() # Clear previous gradients\n",
237
+ " loss.backward() # Compute gradients\n",
238
+ " optimizer.step() # Update model parameters\n",
239
+ "\n",
240
+ " running_loss += loss.item()\n",
241
+ "\n",
242
+ " # Average loss over all batches\n",
243
+ " avg_loss = running_loss / len(train_loader)\n",
244
+ "\n",
245
+ " return avg_loss"
246
+ ],
247
+ "execution_count": null,
248
+ "outputs": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "metadata": {},
253
+ "source": [
254
+ "# Task 3: Write your validation loop here:\n",
255
+ "def validate(model, criterion, test_loader, device):\n",
256
+ " # Set the model to evaluation mode\n",
257
+ " model.eval()\n",
258
+ "\n",
259
+ " running_loss = 0.0\n",
260
+ " correct = 0\n",
261
+ " total = 0\n",
262
+ "\n",
263
+ " with torch.no_grad(): # Disable gradient computation\n",
264
+ " for X_batch, y_batch in test_loader:\n",
265
+ " # Move batch to the selected device\n",
266
+ " X_batch = X_batch.to(device)\n",
267
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
268
+ "\n",
269
+ " # Forward pass\n",
270
+ " outputs = model(X_batch)\n",
271
+ " loss = criterion(outputs, y_batch)\n",
272
+ " running_loss += loss.item()\n",
273
+ "\n",
274
+ " # Binary predictions\n",
275
+ " predicted = (outputs > 0.5).float()\n",
276
+ "\n",
277
+ " # Accuracy calculation\n",
278
+ " correct += (predicted == y_batch).sum().item()\n",
279
+ " total += y_batch.size(0)\n",
280
+ "\n",
281
+ " avg_loss = running_loss / len(test_loader)\n",
282
+ " accuracy = correct / total\n",
283
+ "\n",
284
+ " return avg_loss, accuracy"
285
+ ],
286
+ "execution_count": null,
287
+ "outputs": []
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "metadata": {},
292
+ "source": [
293
+ "# Task 4: Define device, model, loss, optimizer:\n",
294
+ "import torch\n",
295
+ "import torch.nn as nn\n",
296
+ "\n",
297
+ "# Create a linear layer: 3 input features -> 1 output\n",
298
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
299
+ "\n",
300
+ "# Example input: batch of 4 samples, each with 3 features\n",
301
+ "x = torch.randn(4, 3)\n",
302
+ "\n",
303
+ "# Forward through the layer\n",
304
+ "y = linear(x)\n",
305
+ "\n",
306
+ "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n",
307
+ "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n",
308
+ "# Automatically select CPU or GPU\n",
309
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
310
+ "\n",
311
+ "# Create a tensor and move it to GPU\n",
312
+ "x_gpu = x.to(device)\n",
313
+ "print(x_gpu.device) # Output: cuda:0 (if GPU is available) or cpu\n"
314
+ ],
315
+ "execution_count": null,
316
+ "outputs": []
317
+ },
318
+ {
319
+ "cell_type": "code",
320
+ "metadata": {},
321
+ "source": [
322
+ "import torch\n",
323
+ "import torch.nn as nn\n",
324
+ "from torch.optim import Adam\n",
325
+ "import matplotlib.pyplot as plt\n",
326
+ "from sklearn.datasets import load_breast_cancer\n",
327
+ "from sklearn.model_selection import train_test_split\n",
328
+ "from sklearn.preprocessing import StandardScaler\n",
329
+ "from torch.utils.data import TensorDataset\n",
330
+ "from torch.utils.data import DataLoader"
331
+ ],
332
+ "execution_count": null,
333
+ "outputs": []
334
+ },
335
+ {
336
+ "cell_type": "code",
337
+ "metadata": {},
338
+ "source": [
339
+ "# Task 5: Start training for 20 epochs:\n",
340
+ "\n",
341
+ "# Device configuration\n",
342
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
343
+ "print(f\"Using device: {device}\")\n",
344
+ "\n",
345
+ "num_epochs = 20\n",
346
+ "learning_rate = 0.001\n",
347
+ "\n",
348
+ "# Model, Criterion, Optimizer\n",
349
+ "input_dim = X_train.shape[1]\n",
350
+ "hidden_dim = 10\n",
351
+ "model =NN4Layer(input_dim, hidden_dim,output_dim=2).to(device)\n",
352
+ "criterion = nn.BCELoss()\n",
353
+ "optimizer = Adam(model.parameters(), lr=learning_rate)\n",
354
+ "\n",
355
+ "\n",
356
+ "# Run Training\n",
357
+ "train_losses = []\n",
358
+ "val_losses = []\n",
359
+ "val_accuracies = []\n",
360
+ "\n",
361
+ "print('Starting Training...')\n",
362
+ "for epoch in range(num_epochs):\n",
363
+ " # Train one epoch\n",
364
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
365
+ "\n",
366
+ " # Validate\n",
367
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
368
+ "\n",
369
+ " train_losses.append(train_loss)\n",
370
+ " val_losses.append(val_loss)\n",
371
+ " val_accuracies.append(val_accuracy)\n",
372
+ "\n",
373
+ " if (epoch + 1) % 5 == 0:\n",
374
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
375
+ "\n",
376
+ "print('Training Complete!')"
377
+ ],
378
+ "execution_count": null,
379
+ "outputs": []
380
+ },
381
+ {
382
+ "cell_type": "code",
383
+ "metadata": {},
384
+ "source": [
385
+ "# Task 1: Write your code here:\n",
386
+ "# Plotting results\n",
387
+ "plt.figure(figsize=(7, 5))\n",
388
+ "\n",
389
+ "plt.plot(train_losses, label='Train Loss')\n",
390
+ "plt.plot(val_losses, label='Validation Loss')\n",
391
+ "plt.title('Loss over Epochs')\n",
392
+ "plt.xlabel('Epoch')\n",
393
+ "plt.ylabel('Loss')\n",
394
+ "plt.legend()\n",
395
+ "\n",
396
+ "plt.tight_layout()\n",
397
+ "plt.show()"
398
+ ],
399
+ "execution_count": null,
400
+ "outputs": []
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "metadata": {},
405
+ "source": [
406
+ "# Task 2 (Bonus): Write your code here:"
407
+ ],
408
+ "execution_count": null,
409
+ "outputs": []
410
+ }
411
+ ],
412
+ "metadata": {
413
+ "kernelspec": {
414
+ "display_name": "Python 3",
415
+ "name": "python3"
416
+ },
417
+ "language_info": {
418
+ "name": "python"
419
+ }
420
+ },
421
+ "nbformat": 4,
422
+ "nbformat_minor": 0
423
+ }
submissions_extracted/381/Q3.ipynb ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "# Load the dataset\n",
30
+ "data_path = os.path.join(path, 'Q3_data.csv')\n",
31
+ "df_data = pd.read_csv(data_path)"
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
+ "print(f\"Dataset shape: {df_data.shape}\")\n",
42
+ "df_data.head()"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 3: Write your code here:\n",
52
+ "df_data.info()\n"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 4: Write your code here:\n",
62
+ "df_data.describe()\n"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 1: Write your code here:\n",
72
+ "# Analyze missing values\n",
73
+ "missing_percentage = (df_data.isnull().sum() / len(df_data)) * 100\n",
74
+ "missing_data = pd.DataFrame({\n",
75
+ " 'Column': missing_percentage.index,\n",
76
+ " 'Missing_Percentage': missing_percentage.values\n",
77
+ "})\n",
78
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
79
+ "\n",
80
+ "print(\"Missing Data Analysis:\")\n",
81
+ "missing_data.head(10)"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 2: Write your code here:\n",
91
+ "df_data.dropna(subset=['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136'])\n",
92
+ "\n",
93
+ "\n"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 3: Write your code here:\n",
103
+ "from sklearn.preprocessing import StandardScaler\n",
104
+ "\n",
105
+ "numerical_cols = df_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"\") # DON'T SCALE THE TARGET\n",
106
+ "\n",
107
+ "scaler = StandardScaler()\n",
108
+ "df_data[numerical_cols] = scaler.fit_transform(df_data[numerical_cols])\n",
109
+ "df_data.head()\n"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 4: Write your code here:"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# Task 5: Write your code here:"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "# Task 1: Write your code here:"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 2,3,4,5: Write your code here:"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# Task 1: Write your code here:"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# Task 2: Write your code here:"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task Bonus: Write your code here:"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ }
177
+ ],
178
+ "metadata": {
179
+ "kernelspec": {
180
+ "display_name": "Python 3",
181
+ "name": "python3"
182
+ },
183
+ "language_info": {
184
+ "name": "python"
185
+ }
186
+ },
187
+ "nbformat": 4,
188
+ "nbformat_minor": 0
189
+ }
submissions_extracted/382/Q1.ipynb ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
13
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
14
+ "from sklearn.ensemble import RandomForestClassifier\n",
15
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
16
+ "from sklearn.preprocessing import OneHotEncoder\n",
17
+ "\n",
18
+ "# Download latest version\n",
19
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
20
+ "\n",
21
+ "\n",
22
+ "print(\"Path to dataset files:\", path)"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "# Task 1: Write your code here:\n",
32
+ "delivery_path=os.path.join(path,\"Q1_data.csv\")\n",
33
+ "df_delivery=pd.read_csv(delivery_path)\n"
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_delivery.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_delivery.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_delivery.describe()"
64
+ ],
65
+ "execution_count": null,
66
+ "outputs": []
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "metadata": {},
71
+ "source": [
72
+ "# Task 5: Write your code here:\n",
73
+ "plt.figure(figsize=(10,5))\n",
74
+ "plt.hist(df_delivery[\"Delivery_Time\"].dropna(),bins=50,edgecolor='black')\n",
75
+ "plt.title('Delivery Time Distribution')\n",
76
+ "plt.xlabel('Delivery Time')\n",
77
+ "plt.ylabel('Frequancy')\n",
78
+ "plt.show()"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# Task 1: Write your code here:\n"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# Task 2: Write your code here:\n",
97
+ "missing_percentage=(df_delivery.isnull().sum()/len(df_delivery))*100\n",
98
+ "missing_values=pd.DataFrame({'Column':missing_percentage.index,\"Missing_percentage\":missing_percentage.values})\n",
99
+ "missing_values=missing_values[missing_values['Missing_percentage'] > 0].sort_values(\"Missing_percentage\",ascending=False)\n",
100
+ "missing_values.head()\n",
101
+ "subset1=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n",
102
+ "\n",
103
+ "df_clean=df_delivery.dropna(subset=subset1)"
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
+ "duplicate=df_clean.duplicated().sum()\n",
114
+ "print(duplicate)\n",
115
+ "df_clean.drop_duplicates(inplace=True)"
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
+ "categorical=df_clean.select_dtypes(include=['object']).columns\n",
126
+ "print(list(categorical))\n",
127
+ "for col in list(categorical):\n",
128
+ " le=LabelEncoder()\n",
129
+ " df_clean[col]=le.fit_transform(df_clean[col].astype(str))\n"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 5: Write your code here:\n",
139
+ "scaler= StandardScaler()\n",
140
+ "df_clean=scaler.fit_transform(df_clean)"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "# Task 6: Write your code here:\n"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "# Task 1: Write your code here:\n",
159
+ "features=['Vehicle_Type','Preparation_Time_min']\n",
160
+ "X=df_clean[features]\n",
161
+ "y=df_clean['Delivery_Time']\n"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 2,3,4,5: Write your code here:"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 1: Write your code here:\n",
180
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
181
+ "axes = axes.flatten()\n",
182
+ "features = X.columns\n",
183
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
184
+ "\n",
185
+ " absolute_coef = np.abs(coef)\n",
186
+ " sorted_idx = np.argsort(absolute_coef)\n",
187
+ " ax = axes[i]\n",
188
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
189
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
190
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
191
+ " plt.tight_layout()\n",
192
+ " plt.show()"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "# Task 2: Write your code here:"
202
+ ],
203
+ "execution_count": null,
204
+ "outputs": []
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "metadata": {},
209
+ "source": [
210
+ "# Task Bonus: Write your code here:"
211
+ ],
212
+ "execution_count": null,
213
+ "outputs": []
214
+ }
215
+ ],
216
+ "metadata": {
217
+ "kernelspec": {
218
+ "display_name": "Python 3",
219
+ "name": "python3"
220
+ },
221
+ "language_info": {
222
+ "name": "python"
223
+ }
224
+ },
225
+ "nbformat": 4,
226
+ "nbformat_minor": 0
227
+ }
submissions_extracted/382/Q2.ipynb ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "import torch\n",
27
+ "import torch.nn as nn\n",
28
+ "from torch.optim import Adam\n",
29
+ "from torch.utils.data import DataLoader\n",
30
+ "from torchvision.datasets import MNIST\n",
31
+ "from torchvision.transforms import ToTensor, Compose, Normalize\n",
32
+ "from sklearn.decomposition import PCA\n",
33
+ "from sklearn.manifold import TSNE\n",
34
+ "from sklearn.cluster import KMeans\n",
35
+ "import matplotlib.pyplot as plt\n",
36
+ "import numpy as np\n",
37
+ "from collections import Counter\n",
38
+ "from torch.utils.data import TensorDataset\n",
39
+ "import torch.nn.functional as F\n",
40
+ "from torch.optim import AdamW\n",
41
+ "\n",
42
+ "# Load Labels\n",
43
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
44
+ "img_dir = os.path.join(path, \"images\")\n",
45
+ "\n",
46
+ "images = []\n",
47
+ "ages = []\n",
48
+ "\n",
49
+ "# Load Images and Resize\n",
50
+ "print(\"Loading images...\")\n",
51
+ "for index, row in labels_df.iterrows():\n",
52
+ " img_name = row.iloc[0]\n",
53
+ " age = row.iloc[1]\n",
54
+ " img_path = os.path.join(img_dir, img_name)\n",
55
+ "\n",
56
+ " if os.path.exists(img_path):\n",
57
+ " img = Image.open(img_path).convert('RGB')\n",
58
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
59
+ " images.append(img_array)\n",
60
+ " ages.append(age)\n",
61
+ "\n",
62
+ "X = np.array(images)\n",
63
+ "y = np.array(ages)\n",
64
+ "\n",
65
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
66
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
67
+ "\n",
68
+ "# Split Data\n",
69
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
70
+ "\n",
71
+ "print(f\"X_train shape: {X_train.shape}\")\n",
72
+ "print(f\"X_test shape: {X_test.shape}\")\n",
73
+ "print(f\"y_train shape: {y_train.shape}\")\n",
74
+ "print(f\"y_test shape: {y_test.shape}\")"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
84
+ "X_train = torch.tensor(X_train, dtype=torch.float32).flatten()\n",
85
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
86
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
87
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
88
+ "\n"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# 2. Create TensorDataset objects\n",
98
+ "train_dataset=TensorDataset(X_train,y_train)\n",
99
+ "test_dataset=TensorDataset(X_test,y_test)\n",
100
+ "\n"
101
+ ],
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(\n",
112
+ "train_dataset,\n",
113
+ "batch_size=32,\n",
114
+ "shuffle=True,\n",
115
+ "num_workers=2)\n",
116
+ "test_loader = DataLoader(\n",
117
+ "test_dataset,\n",
118
+ "batch_size=32,\n",
119
+ "shuffle=False,)\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
+ "\n"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# 5. Display sample images\n",
139
+ "images,labels=next(iter(train_dataset))\n",
140
+ "plt.figure(figsize=(20,4))\n",
141
+ "for i in range(2):\n",
142
+ " plt.subplot(2, 3, i + 1)\n",
143
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
144
+ " plt.axis('off')\n",
145
+ " plt.tight_layout()\n",
146
+ " plt.show()\n",
147
+ "\n"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 1: Write your model class here:\n",
157
+ "class NN4Layer(nn.Module):\n",
158
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
159
+ " super(NN4Layer, self).__init__()\n",
160
+ "\n",
161
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
162
+ "\n",
163
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
164
+ "\n",
165
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
166
+ "\n",
167
+ " self.layer4=nn.Linear(hidden_dim,output_dim)\n",
168
+ "\n",
169
+ " self.relu = nn.ReLU()\n",
170
+ "\n",
171
+ " def forward(self, x):\n",
172
+ "\n",
173
+ " z1 = self.layer1(x)\n",
174
+ " a1 = self.relu(z1)\n",
175
+ "\n",
176
+ " z2 = self.layer2(a1)\n",
177
+ " a2 = self.relu(z2)\n",
178
+ " z3=self.layer3(a2)\n",
179
+ " a3=self.relu(z3)\n",
180
+ " output = self.layer4(a3)\n",
181
+ " return output"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 2: Write your training loop here:\n",
191
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
192
+ " model.train()\n",
193
+ " running_loss = 0.0\n",
194
+ " for X_batch, y_batch in train_loader:\n",
195
+ "\n",
196
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
197
+ " y_batch = y_batch.to(device)\n",
198
+ "\n",
199
+ " outputs = model(X_batch)\n",
200
+ " loss = criterion(outputs, y_batch)\n",
201
+ " optimizer.zero_grad()\n",
202
+ " loss.backward()\n",
203
+ " optimizer.step()\n",
204
+ " running_loss += loss.item()\n",
205
+ ""
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Task 3: Write your validation loop here:\n",
215
+ "def validate(model, criterion, test_loader, device):\n",
216
+ " model.eval()\n",
217
+ " running_loss = 0.0\n",
218
+ "\n",
219
+ " with torch.no_grad():\n",
220
+ " for X_batch, y_batch in test_loader:\n",
221
+ "\n",
222
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
223
+ " y_batch = y_batch.to(device)\n",
224
+ "\n",
225
+ " outputs = model(X_batch.viewsview(images.size(0), -1))\n",
226
+ " loss = criterion(outputs, y_batch)\n",
227
+ " running_loss += loss.item()\n",
228
+ "\n",
229
+ "\n",
230
+ ""
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "metadata": {},
238
+ "source": [
239
+ "# Task 4: Define device, model, loss, optimizer:\n",
240
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
241
+ "input_dim=2000\n",
242
+ "hidden_dim=14\n",
243
+ "output_dim=101\n",
244
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
245
+ "loss=nn.MSELoss()\n",
246
+ "num_epochs=20\n",
247
+ "learning_rate=0.01\n",
248
+ "optimizer=AdamW(model.parameters(),learning_rate)\n"
249
+ ],
250
+ "execution_count": null,
251
+ "outputs": []
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "metadata": {},
256
+ "source": [
257
+ "# Task 5: Start training for 20 epochs:\n",
258
+ "train_losses=[]\n",
259
+ "test_losses=[]\n",
260
+ "print('Starting Training...')\n",
261
+ "for epoch in range(num_epochs):\n",
262
+ "\n",
263
+ " train_loss = train_one_epoch(model, optimizer, loss, train_loader, device)\n",
264
+ "\n",
265
+ " val_loss, val_accuracy = validate(model, loss, test_loader, device)\n",
266
+ " train_losses.append(train_loss)\n",
267
+ " test_losses.append(val_loss)\n",
268
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Task 1: Write your code here:\n",
278
+ "plt.figure(figsize=(10, 5))\n",
279
+ "plt.plot(train_losses, 'b-o')\n",
280
+ "plt.xlabel('Epoch')\n",
281
+ "plt.ylabel('MSE Loss')\n",
282
+ "plt.title('Autoencoder Training Loss')\n",
283
+ "plt.grid(True, alpha=0.3)\n",
284
+ "plt.show()"
285
+ ],
286
+ "execution_count": null,
287
+ "outputs": []
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "metadata": {},
292
+ "source": [
293
+ "# Task 2 (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/382/Q3.ipynb ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os\n",
13
+ "\n",
14
+ "\n",
15
+ "\n",
16
+ "# Download latest version\n",
17
+ "\n",
18
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
19
+ "\n",
20
+ "\n",
21
+ "\n",
22
+ "print(\"Path to dataset files:\", path)"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "# Task 1: Write your code here:\n",
32
+ "cvs_path=os.path.join(path,'Q3_data.csv')\n",
33
+ "df_card=pd.read_csv(cvs_path)"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 2: Write your code here:\n",
43
+ "df_card.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_card.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_card.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
+ "df_card['Target'] = df_card['Target'].map({'Default': 1, 'No Default': 0})\n",
74
+ "missing_values = df_card.dropna()\n",
75
+ "\n",
76
+ "\n",
77
+ "\n"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 2: Write your code here:\n",
87
+ "duplicates = df_card.duplicated().sum()\n",
88
+ "print(f\"Number of Duplicate Samples: {duplicates}\")\n",
89
+ "if duplicates > 0:\n",
90
+ " print(\"Dropping Duplicates...\")\n",
91
+ " df_card.drop_duplicates(inplace=True)\n",
92
+ " print(\"Duplicates Dropped.\")\n",
93
+ "else:\n",
94
+ " print(\"No Duplicate Samples Found.\")"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 3: Write your code here:\n",
104
+ "categorical_cols = df_card.select_dtypes(include=[\"object\"]).columns\n",
105
+ "print(\"Categorical Columns:\", list(categorical_cols))"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# Task 4: Write your code here:\n",
115
+ "from sklearn.preprocessing import StandardScaler\n",
116
+ "numerical_cols = df_card.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
117
+ "scaler = StandardScaler()\n",
118
+ "df_card[numerical_cols] = scaler.fit_transform(df_card[numerical_cols])\n",
119
+ "df_card.head()"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 5: Write your code here:\n",
129
+ "print(\"Target Distribution:\")\n",
130
+ "print(df_card['Target'].value_counts(normalize=True))\n",
131
+ "sns.countplot(x=df_card['Target'])\n",
132
+ "plt.title(\"Target Distribution\")\n",
133
+ "plt.show()"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 1: Write your code here:\n",
143
+ "X = df_card.drop(\"Target\", axis=1).astype(float)\n",
144
+ "y = df_card['Target'].astype(float)"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "# Task 2,3,4,5: Write your code here:\n",
154
+ "from tqdm import tqdm\n",
155
+ "def sigmoid(z):\n",
156
+ " return 1 / (1 + np.exp(-z))\n",
157
+ "def binary_cross_entropy(y, y_hat):\n",
158
+ " epsilon = 1e-15 # Very small number to prevent log(0)\n",
159
+ " y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
160
+ " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
161
+ " return loss\n",
162
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
163
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
164
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
165
+ " losses = []\n",
166
+ " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
167
+ " z = np.dot(X, theta)\n",
168
+ " y_hat = sigmoid(z)\n",
169
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
170
+ " theta -= learning_rate * gradient\n",
171
+ " loss = binary_cross_entropy(y, y_hat)\n",
172
+ " losses.append(loss)\n",
173
+ " return theta, losses\n",
174
+ "from sklearn.model_selection import StratifiedKFold\n",
175
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
176
+ "n_splits = 5\n",
177
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
178
+ "lr_losses = []\n",
179
+ "lr_accuracy = []\n",
180
+ "lr_f1 = []\n",
181
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
182
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
183
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
184
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
185
+ "\n",
186
+ " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
187
+ "\n",
188
+ " y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
189
+ " y_pred = (y_pred_proba >= 0.5).astype(int)\n",
190
+ "\n",
191
+ " accuracy = accuracy_score(y_test, y_pred)\n",
192
+ "\n",
193
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
194
+ "\n",
195
+ " lr_losses.append(losses)\n",
196
+ " lr_accuracy.append(accuracy)\n",
197
+ "\n",
198
+ " lr_f1.append(f1)"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "# Task 1: Write your code here:\n",
208
+ "avg_loss = np.mean(lr_losses, axis=0)\n",
209
+ "plt.figure(figsize=(10, 6))\n",
210
+ "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
211
+ "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
212
+ "plt.xlabel('Iteration')\n",
213
+ "plt.ylabel('Binary Cross-Entropy Loss')\n",
214
+ "plt.legend()\n",
215
+ "plt.grid(True, alpha=0.3)\n",
216
+ "plt.show()"
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "# Task 2: Write your code here:"
226
+ ],
227
+ "execution_count": null,
228
+ "outputs": []
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "metadata": {},
233
+ "source": [
234
+ "# Task Bonus: Write your code here:"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ }
239
+ ],
240
+ "metadata": {
241
+ "kernelspec": {
242
+ "display_name": "Python 3",
243
+ "name": "python3"
244
+ },
245
+ "language_info": {
246
+ "name": "python"
247
+ }
248
+ },
249
+ "nbformat": 4,
250
+ "nbformat_minor": 0
251
+ }
submissions_extracted/383/Q1.ipynb ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sklearn.preprocessing import LabelEncoder,StandardScaler\n",
14
+ "from sklearn.model_selection import train_test_split,KFold\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "\n",
17
+ "from sklearn.metrics import mean_absolute_error\n"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [],
26
+ "execution_count": null,
27
+ "outputs": []
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "metadata": {},
32
+ "source": [
33
+ "import kagglehub\n",
34
+ "\n",
35
+ "# Download latest version\n",
36
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
37
+ "\n",
38
+ "print(\"Path to dataset files:\", path)"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 1: Write your code here:\n",
48
+ "#/kaggle/input/q1-exam-data/Q1_data.csv\n",
49
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
50
+ "df = pd.read_csv(csv_path)"
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
+ "\n",
61
+ "df.head(10)"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 3: Write your code here:\n",
71
+ "df.info()"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# Task 4: Write your code here:\n",
81
+ "df.describe()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 5: Write your code here:\n",
91
+ "def check_target_distribution(df, target_column):\n",
92
+ " df[target_column].hist(bins=30, edgecolor='black')\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
+ " plt.show()\n",
98
+ "\n",
99
+ "check_target_distribution(df, \"Delivery_Time\")"
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 = df.drop(columns=\"Order_ID\", axis=1)\n",
110
+ "df"
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
+ "#calculting the missing percentage so that i thing what i do with them\n",
121
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
122
+ "\n",
123
+ "missing_data = pd.DataFrame({\n",
124
+ " 'Column': missing_percentage.index,\n",
125
+ " 'Missing_Percentage': missing_percentage.values\n",
126
+ "})\n",
127
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
128
+ "print(\"Missing Data Analysis:\")\n",
129
+ "missing_data.head(10)"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "df_clean = df.copy() #first lets copy\n",
139
+ "df_clean = df_clean.dropna(subset=[\"Delivery_Time\"]) #drop the na smaples in target\n",
140
+ "\n",
141
+ "columns_to_mode = ['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n",
142
+ "\n",
143
+ "for col in columns_to_mode:\n",
144
+ " df_clean[col]=df_clean[col].fillna(df_clean[col].mode()[0]) #i want descret numbers\n",
145
+ "\n",
146
+ "\n",
147
+ "\n"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "df_clean.head()"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task 3: Write your code here:\n",
173
+ "def check_duplicates(df_clean):\n",
174
+ " # duplicated().sum(): Counts identical rows.\n",
175
+ " duplicates = df_clean.duplicated().sum()\n",
176
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
177
+ "\n",
178
+ " if duplicates > 0:\n",
179
+ " print(\"Dropping Duplicates...\")\n",
180
+ " # inplace=True: Modifies the actual DataFrame, doesn't return a copy.\n",
181
+ " df_clean.drop_duplicates(inplace=True)\n",
182
+ " print(\"Duplicates Dropped.\")\n",
183
+ " else:\n",
184
+ " print(\"No Duplicate Samples Found.\")\n",
185
+ "\n",
186
+ "check_duplicates(df)"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "metadata": {},
194
+ "source": [
195
+ "df_clean.shape"
196
+ ],
197
+ "execution_count": null,
198
+ "outputs": []
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "metadata": {},
203
+ "source": [
204
+ "# Task 4: Write your code here:\n",
205
+ "catogerical = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
206
+ "le = LabelEncoder()\n",
207
+ "for col in catogerical:\n",
208
+ " df_clean[col]=le.fit_transform(df_clean[col])\n",
209
+ "df_clean.head()"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "#i want to do scale on the train only\n",
219
+ "X = df_clean.drop('Delivery_Time',axis=1)\n",
220
+ "y= df_clean['Delivery_Time']\n",
221
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n"
222
+ ],
223
+ "execution_count": null,
224
+ "outputs": []
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "metadata": {},
229
+ "source": [
230
+ "# Task 5: Write your code here:\n",
231
+ "standard_scaler = StandardScaler()\n",
232
+ "X_train_scaled = standard_scaler.fit_transform(X_train)\n",
233
+ "X_test_scaled = standard_scaler.transform(X_test)"
234
+ ],
235
+ "execution_count": null,
236
+ "outputs": []
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "metadata": {},
241
+ "source": [
242
+ "# Task 6: Write your code here:\n",
243
+ "# even if its imbalance, we dont care it is regression\n",
244
+ "target=df_clean['Delivery_Time'].value_counts()\n",
245
+ "target"
246
+ ],
247
+ "execution_count": null,
248
+ "outputs": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "metadata": {},
253
+ "source": [
254
+ "# Task 1: Write your code here:\n",
255
+ "# i did it above becaus i want to do the scalte on the train only so no data leake\n",
256
+ "#i used kfold only becuse it is regression"
257
+ ],
258
+ "execution_count": null,
259
+ "outputs": []
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "metadata": {},
264
+ "source": [
265
+ "# Task 2,3,4,5: Write your code here:\n",
266
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
267
+ "\n",
268
+ "model.fit(X_train_scaled, y_train)\n",
269
+ "print(\"Model trained!\")\n",
270
+ "\n",
271
+ "y_pred = model.predict(X_test_scaled)\n",
272
+ "mae = mean_absolute_error(y_test, y_pred)\n",
273
+ "print(f\"MAE: ${mae:,.2f}\")\n",
274
+ "\n",
275
+ "\n",
276
+ "\n",
277
+ "kfold = KFold(n_splits=3, shuffle=True, random_state=42)\n",
278
+ "mae_scores = []\n",
279
+ "for train_idx, val_idx in kfold.split(X_train_scaled):\n",
280
+ " # Slice the arrays\n",
281
+ " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
282
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
283
+ "\n",
284
+ " # Train and predict\n",
285
+ " model.fit(X_fold_train, y_fold_train)\n",
286
+ " y_fold_pred = model.predict(X_fold_val)\n",
287
+ "\n",
288
+ " # Calculate metrics for this specific fold\n",
289
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
290
+ "mae_scores = np.array(mae_scores)\n",
291
+ "print(f\"5-Fold CV Results:\")\n",
292
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")\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
+ "\n",
303
+ "feature_cols=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
304
+ "feature_importance = pd.DataFrame({\n",
305
+ " 'feature': feature_cols,\n",
306
+ " 'importance': model.feature_importances_\n",
307
+ "}).sort_values('importance', ascending=False)\n",
308
+ "\n",
309
+ "plt.figure(figsize=(10, 6))\n",
310
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
311
+ "plt.xlabel('Importance')\n",
312
+ "plt.title('Feature Importance')\n",
313
+ "plt.gca().invert_yaxis()\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
+ "plt.figure(figsize=(10, 5))\n",
325
+ "plt.hist(y_pred, bins=50, edgecolor='black')\n",
326
+ "plt.title('predicted Distribution')\n",
327
+ "plt.xlabel('time in mins')\n",
328
+ "plt.ylabel('Frequency')\n",
329
+ "plt.show()"
330
+ ],
331
+ "execution_count": null,
332
+ "outputs": []
333
+ },
334
+ {
335
+ "cell_type": "code",
336
+ "metadata": {},
337
+ "source": [
338
+ "# Task Bonus: Write your code here:"
339
+ ],
340
+ "execution_count": null,
341
+ "outputs": []
342
+ }
343
+ ],
344
+ "metadata": {
345
+ "kernelspec": {
346
+ "display_name": "Python 3",
347
+ "name": "python3"
348
+ },
349
+ "language_info": {
350
+ "name": "python"
351
+ }
352
+ },
353
+ "nbformat": 4,
354
+ "nbformat_minor": 0
355
+ }
submissions_extracted/383/Q2.ipynb ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [],
7
+ "execution_count": null,
8
+ "outputs": []
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "metadata": {},
13
+ "source": [
14
+ "import torch\n",
15
+ "import torch.nn as nn\n",
16
+ "from torchvision.datasets import MNIST\n",
17
+ "from torch.utils.data import DataLoader,TensorDataset\n",
18
+ "from torch.optim import AdamW\n",
19
+ "from torchvision.transforms.functional import to_tensor\n",
20
+ "import torch.nn.functional as F\n",
21
+ "import matplotlib.pyplot as plt"
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
+ "# Float for inputs, Long for classification targets, Float for regression targets\n",
93
+ "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
94
+ "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n",
95
+ "\n",
96
+ "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
97
+ "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n",
98
+ "\n"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# 2. Create TensorDataset objects\n",
108
+ "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
109
+ "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n",
110
+ "\n"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "# 3. Create DataLoaders\n",
120
+ "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n",
121
+ "test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\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}\")"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# 5. Display sample images\n",
144
+ "# Get one batch of images and labels\n",
145
+ "images, labels = next(iter(train_loader))\n",
146
+ "\n",
147
+ "# Display the first 6 images in the batch\n",
148
+ "plt.figure(figsize=(8, 4))\n",
149
+ "\n",
150
+ "for i in range(6):\n",
151
+ " plt.subplot(2, 3, i + 1)\n",
152
+ " # .squeeze() removes the channel dimension (1, 28, 28) -> (28, 28) for matplotlib\n",
153
+ " img = images[i].permute(1, 2, 0)\n",
154
+ " plt.imshow(img)\n",
155
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
156
+ " plt.axis('off')\n",
157
+ "\n",
158
+ "plt.tight_layout()\n",
159
+ "plt.show()\n"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your model class here:\n",
169
+ "class NN4Layer(nn.Module):\n",
170
+ "\n",
171
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
172
+ " super(NN4Layer, self).__init__()\n",
173
+ "\n",
174
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
175
+ "\n",
176
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
177
+ "\n",
178
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
179
+ "\n",
180
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
181
+ "\n",
182
+ "\n",
183
+ "\n",
184
+ " # activation function 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
+ " z1 = self.layer1(x)\n",
190
+ " a1 = self.relu(z1)\n",
191
+ "\n",
192
+ " z2 = self.layer2(a1)\n",
193
+ " a2 = self.relu(z2)\n",
194
+ "\n",
195
+ " z3 = self.layer3(a2)\n",
196
+ " a3 = self.relu(z3)\n",
197
+ "\n",
198
+ " # Layer 4 TODO\n",
199
+ " z4 = self.layer4(a3)\n",
200
+ "\n",
201
+ "\n",
202
+ "\n",
203
+ "\n",
204
+ " # TODO: are we missing output activation function? (hint: Loss Function)\n",
205
+ "\n",
206
+ " return z4"
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
+ " running_loss = 0.0\n",
220
+ "\n",
221
+ " for X_batch, y_batch in train_loader:\n",
222
+ " X_batch =X_batch.view(X_batch.size(0), -1).to(device)\n",
223
+ " y_batch = y_batch.to(device)\n",
224
+ "\n",
225
+ " outputs = model(X_batch)\n",
226
+ " loss = criterion(outputs, y_batch)\n",
227
+ "\n",
228
+ "\n",
229
+ " optimizer.zero_grad()\n",
230
+ " loss.backward()\n",
231
+ " optimizer.step()\n",
232
+ "\n",
233
+ " running_loss += loss.item()\n",
234
+ "\n",
235
+ " avg_loss = running_loss / len(train_loader)\n",
236
+ " return avg_loss"
237
+ ],
238
+ "execution_count": null,
239
+ "outputs": []
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "metadata": {},
244
+ "source": [
245
+ "# Task 3: Write your validatio\n",
246
+ "def validate(model, criterion, test_loader, device):\n",
247
+ " # Set the model to evaluation mode\n",
248
+ "\n",
249
+ " model.eval()\n",
250
+ " running_loss = 0.0\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
+ " outputs = model(X_batch)\n",
258
+ " loss = criterion(outputs, y_batch)\n",
259
+ " running_loss += loss.item()\n",
260
+ " avg_loss = running_loss / len(test_loader)\n",
261
+ " return avg_loss"
262
+ ],
263
+ "execution_count": null,
264
+ "outputs": []
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "metadata": {},
269
+ "source": [
270
+ "# Task 4: Define device, model, loss, optimizer:\n",
271
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
272
+ "input_dim = 3*36*36\n",
273
+ "hidden_dim = 64\n",
274
+ "output_dim = 1\n",
275
+ "\n",
276
+ "\n",
277
+ "num_epochs = 20\n",
278
+ "learning_rate = 0.001\n",
279
+ "\n",
280
+ "model=NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
281
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
282
+ "criterion = nn.MSELoss()"
283
+ ],
284
+ "execution_count": null,
285
+ "outputs": []
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "metadata": {},
290
+ "source": [
291
+ "print(\"Model Architecture:\\n\")\n",
292
+ "print(model)"
293
+ ],
294
+ "execution_count": null,
295
+ "outputs": []
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "metadata": {},
300
+ "source": [
301
+ "# Task 5: Start training for 20 epochs:\n",
302
+ "train_losses = []\n",
303
+ "val_losses = []\n",
304
+ "val_accuracies = []\n",
305
+ "\n",
306
+ "print('Starting Training...')\n",
307
+ "for epoch in range(num_epochs):\n",
308
+ " # Train one epoch\n",
309
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
310
+ "\n",
311
+ " # Validate\n",
312
+ " val_loss = validate(model, criterion, test_loader, device)\n",
313
+ "\n",
314
+ " train_losses.append(train_loss)\n",
315
+ " val_losses.append(val_loss)\n",
316
+ "\n",
317
+ "\n",
318
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}')\n",
319
+ "\n",
320
+ "print('Training Complete!')"
321
+ ],
322
+ "execution_count": null,
323
+ "outputs": []
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "metadata": {},
328
+ "source": [
329
+ "# Task 1: Write your code here:\n",
330
+ "plt.figure(figsize=(7, 5))\n",
331
+ "\n",
332
+ "plt.plot(train_losses, label='Train Loss')\n",
333
+ "plt.plot(val_losses, label='Validation Loss')\n",
334
+ "plt.title('Loss over Epochs')\n",
335
+ "plt.xlabel('Epoch')\n",
336
+ "plt.ylabel('Loss')\n",
337
+ "plt.legend()\n",
338
+ "\n",
339
+ "plt.tight_layout()\n",
340
+ "plt.show()"
341
+ ],
342
+ "execution_count": null,
343
+ "outputs": []
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "metadata": {},
348
+ "source": [
349
+ "# Task 2 (Bonus): Write your code here:"
350
+ ],
351
+ "execution_count": null,
352
+ "outputs": []
353
+ }
354
+ ],
355
+ "metadata": {
356
+ "kernelspec": {
357
+ "display_name": "Python 3",
358
+ "name": "python3"
359
+ },
360
+ "language_info": {
361
+ "name": "python"
362
+ }
363
+ },
364
+ "nbformat": 4,
365
+ "nbformat_minor": 0
366
+ }
submissions_extracted/383/Q3.ipynb ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "from IPython.display import clear_output\n",
8
+ "\n",
9
+ "%pip install kagglehub catboost xgboost tqdm -q\n",
10
+ "clear_output()\n"
11
+ ],
12
+ "execution_count": null,
13
+ "outputs": []
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "metadata": {},
18
+ "source": [
19
+ "import pandas as pd\n",
20
+ "import numpy as np\n",
21
+ "import matplotlib.pyplot as plt\n",
22
+ "import seaborn as sns\n",
23
+ "import kagglehub\n",
24
+ "import os\n",
25
+ "from tqdm import tqdm\n",
26
+ "from sklearn.preprocessing import StandardScaler\n"
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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
56
+ "\n",
57
+ "df = pd.read_csv(csv_path)\n"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 2: Write your code here:\n",
67
+ "df.head()"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# Task 3: Write your code here:\n",
77
+ "df.info()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 4: Write your code here:\n",
87
+ "df.describe()"
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
+ "# Do we have missing values?\n",
98
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
99
+ "\n",
100
+ "missing_data = pd.DataFrame({\n",
101
+ " 'Column': missing_percentage.index,\n",
102
+ " 'Missing_Percentage': missing_percentage.values\n",
103
+ "})\n",
104
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
105
+ "print(\"Missing Data Analysis:\")\n",
106
+ "missing_data.head(10)"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "df_clean = df.copy()\n",
116
+ "df_clean = df_clean.drop(columns=['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136']) #drop the na smaples in target\n"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# Task 2: Write your code here:\n",
126
+ "def check_duplicates(df_clean):\n",
127
+ " duplicates = df_clean.duplicated().sum()\n",
128
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
129
+ " if duplicates > 0:\n",
130
+ " print(\"Dropping Duplicates...\")\n",
131
+ " df_clean.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_clean)\n"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 3: Write your code here:\n",
146
+ "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
147
+ "\n",
148
+ "print(\"Categorical Columns:\", list(categorical_cols))"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 4: Write your code here:\n",
158
+ "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
159
+ "\n",
160
+ "# StandardScaler: (x - mean) / std (Z-score normalization)\n",
161
+ "scaler = StandardScaler()\n",
162
+ "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
163
+ "df_clean.head()"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task 5: Write your code here:\n",
173
+ "target=df_clean['Target'].value_counts()\n",
174
+ "target"
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.drop(\"Target\", axis=1)\n",
185
+ "y = df['Target']"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 2,3,4,5: Write your code here:\n",
195
+ "from sklearn.model_selection import StratifiedKFold\n",
196
+ "from catboost import CatBoostClassifier\n",
197
+ "\n",
198
+ "n_splits = 5\n",
199
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
200
+ "\n",
201
+ "\n",
202
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
203
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
204
+ "\n",
205
+ " # 1. Split data\n",
206
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
207
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
208
+ "\n",
209
+ " model=CatBoostClassifier(\n",
210
+ " verbose=0, # Silence training log\n",
211
+ " n_estimators=320,\n",
212
+ " max_depth=4\n",
213
+ " )\n",
214
+ "\n",
215
+ " model.fit(X_train, y_train)\n",
216
+ " y_pred = model.predict(X_test)\n",
217
+ "\n"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "majority_class = y.value_counts().idxmax()\n",
227
+ "baseline_pred = [majority_class] * len(y)\n",
228
+ "baseline_accuracy = accuracy_score(y, baseline_pred)\n",
229
+ "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "# Task 1: Write your code here:"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [
247
+ "# Task 2: Write your code here:"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "# Task Bonus: Write your code here:"
257
+ ],
258
+ "execution_count": null,
259
+ "outputs": []
260
+ }
261
+ ],
262
+ "metadata": {
263
+ "kernelspec": {
264
+ "display_name": "Python 3",
265
+ "name": "python3"
266
+ },
267
+ "language_info": {
268
+ "name": "python"
269
+ }
270
+ },
271
+ "nbformat": 4,
272
+ "nbformat_minor": 0
273
+ }
submissions_extracted/384/Q1.ipynb ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "# Task 1: Write your code here:\n",
23
+ "import pandas as pd\n",
24
+ "import numpy as np\n",
25
+ "import matplotlib.pyplot as plt\n",
26
+ "import seaborn as sns\n",
27
+ "import kagglehub\n",
28
+ "import os\n",
29
+ "from tqdm import tqdm\n",
30
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
31
+ "\n",
32
+ "df = pd.read_csv(csv_path)\n"
33
+ ],
34
+ "execution_count": null,
35
+ "outputs": []
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "metadata": {},
40
+ "source": [
41
+ "# Task 2: Write your code here:\n",
42
+ "df.head()"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 3: Write your code here:\n",
52
+ "df.info()"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 4: Write your code here:\n",
62
+ "df.describe()"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 5: Write your code here:\n",
72
+ "plt.figure(figsize=(10, 5))\n",
73
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
74
+ "plt.title('Delivery_Time Distribution')\n",
75
+ "plt.xlabel('Delivery_Time')\n",
76
+ "plt.ylabel('Frequency')\n",
77
+ "plt.show()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 1: Write your code here:\n",
87
+ "df = df.drop(columns=\"Order_ID\", axis=1)\n",
88
+ "df.head()\n"
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_missing_values(df):\n",
99
+ " missing_values = df.isnull().sum()\n",
100
+ " print(\"Missing Values per Column:\")\n",
101
+ " print(missing_values[missing_values > 0])\n",
102
+ " if missing_values.any():\n",
103
+ " print(\"\\nHandle Missing Values as needed.\")\n",
104
+ " else:\n",
105
+ " print(\"\\nNo Missing Values Found.\")\n",
106
+ "\n",
107
+ "check_missing_values(df)"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n",
117
+ "df_clean = df[cols].copy()\n",
118
+ "\n",
119
+ "# Drop rows where target missing - can't predict without them\n",
120
+ "print(f\"Before: {df_clean.shape}\")\n",
121
+ "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n",
122
+ "print(f\"After dropping missing : {df_clean.shape}\")"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "check_missing_values(df_clean)"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# # Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
141
+ "for col in ['Weather', 'Traffic_Level', 'Time_of_Day''Time_of_Day', 'Vehicle_Type']:\n",
142
+ " df_clean[col] = df_clean[col].fillna('unknown')\n",
143
+ "\n",
144
+ "#Fill Courier_Experience_yrs with mean\n",
145
+ "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n",
146
+ "\n",
147
+ "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 3: Write your code here:\n",
157
+ "# 4. Do we have duplicate samples?\n",
158
+ "def check_duplicates(df):\n",
159
+ " duplicates = df.duplicated().sum()\n",
160
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
161
+ " if duplicates > 0:\n",
162
+ " print(\"Dropping Duplicates...\")\n",
163
+ " df.drop_duplicates(inplace=True)\n",
164
+ " print(\"Duplicates Dropped.\")\n",
165
+ " else:\n",
166
+ " print(\"No Duplicate Samples Found.\")\n",
167
+ "\n",
168
+ "check_duplicates(df)"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 3: Write your code here:\n",
178
+ "# 4. Do we have duplicate samples?\n",
179
+ "def check_duplicates(df_clean):\n",
180
+ " duplicates = df_clean.duplicated().sum()\n",
181
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
182
+ " if duplicates > 0:\n",
183
+ " print(\"Dropping Duplicates...\")\n",
184
+ " df_clean.drop_duplicates(inplace=True)\n",
185
+ " print(\"Duplicates Dropped.\")\n",
186
+ " else:\n",
187
+ " print(\"No Duplicate Samples Found.\")\n",
188
+ "\n",
189
+ "check_duplicates(df_clean)"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 4: Write your code here:\n",
199
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
200
+ "\n",
201
+ "catog = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
202
+ "#categories = pd.DataFrame(catog)\n",
203
+ "catog\n"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n",
213
+ "\n",
214
+ "print('data before encoding:\\n', catog) #show before encoding\n",
215
+ "\n",
216
+ "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n",
217
+ "data_label_encoded = label_encoder.fit_transform(catog) # Apply fit_transform to the column\n",
218
+ "\n",
219
+ "print('\\nData after encoding:\\n', data_label_encoded) #show after encoding"
220
+ ],
221
+ "execution_count": null,
222
+ "outputs": []
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "metadata": {},
227
+ "source": [
228
+ "from sklearn.preprocessing import LabelEncoder\n",
229
+ "# 3. Do we have categorical columns?\n",
230
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
231
+ "\n",
232
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
233
+ "label_encoders = {}\n",
234
+ "for col in categorical_cols:\n",
235
+ " le = LabelEncoder()\n",
236
+ " df[col] = le.fit_transform(df[col])\n",
237
+ " label_encoders[col] = le\n",
238
+ "\n",
239
+ "df"
240
+ ],
241
+ "execution_count": null,
242
+ "outputs": []
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "metadata": {},
247
+ "source": [
248
+ "\n",
249
+ "# onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
250
+ "# data_onehot_encoded = onehot_encoder.fit_transform(cols) # Apply fit_transform to the copied\n",
251
+ "\n",
252
+ "# print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "from sklearn.preprocessing import StandardScaler\n",
262
+ "\n",
263
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") #we shouldnt SCALE THE TARGET\n",
264
+ "\n",
265
+ "scaler = StandardScaler()\n",
266
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
267
+ "df.head()\n"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task 6: Write your code here:\n",
277
+ "# 1. Is the target imbalanced?\n",
278
+ "def check_target_imbalance(df, target_column):\n",
279
+ " print(\"Target Distribution:\")\n",
280
+ "\n",
281
+ " df[target_column].hist()\n",
282
+ " plt.show()\n",
283
+ "\n",
284
+ "check_target_imbalance(df, \"Delivery_Time\")"
285
+ ],
286
+ "execution_count": null,
287
+ "outputs": []
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "metadata": {},
292
+ "source": [
293
+ "from sklearn.linear_model import Ridge, Lasso\n",
294
+ "from sklearn.svm import SVR\n",
295
+ "from sklearn.tree import DecisionTreeRegressor\n",
296
+ "from sklearn.ensemble import RandomForestRegressor\n",
297
+ "from lightgbm import LGBMRegressor\n",
298
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
299
+ "\n"
300
+ ],
301
+ "execution_count": null,
302
+ "outputs": []
303
+ },
304
+ {
305
+ "cell_type": "code",
306
+ "metadata": {},
307
+ "source": [
308
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
309
+ "y = df['Delivery_Time'].astype(float)"
310
+ ],
311
+ "execution_count": null,
312
+ "outputs": []
313
+ },
314
+ {
315
+ "cell_type": "code",
316
+ "metadata": {},
317
+ "source": [
318
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
319
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
320
+ ],
321
+ "execution_count": null,
322
+ "outputs": []
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "metadata": {},
327
+ "source": [
328
+ "from sklearn.model_selection import StratifiedKFold\n",
329
+ "from sklearn.model_selection import train_test_split\n",
330
+ "\n",
331
+ "n_splits = 3 # K\n",
332
+ "\n",
333
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
334
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
335
+ ],
336
+ "execution_count": null,
337
+ "outputs": []
338
+ },
339
+ {
340
+ "cell_type": "code",
341
+ "metadata": {},
342
+ "source": [
343
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
344
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
345
+ "\n",
346
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
347
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]"
348
+ ],
349
+ "execution_count": null,
350
+ "outputs": []
351
+ },
352
+ {
353
+ "cell_type": "code",
354
+ "metadata": {},
355
+ "source": [
356
+ "# Train Random Forest Regressor\n",
357
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
358
+ "model.fit(X_train, y_train)\n",
359
+ "print(\"Model trained!\")"
360
+ ],
361
+ "execution_count": null,
362
+ "outputs": []
363
+ },
364
+ {
365
+ "cell_type": "code",
366
+ "metadata": {},
367
+ "source": [
368
+ "# Predict and evaluate\n",
369
+ "y_pred = model.predict(X_test)\n",
370
+ "\n",
371
+ "mae = mean_absolute_error(y_test, y_pred)\n",
372
+ "\n",
373
+ "print(f\"MAE: ${mae:,.2f}\")\n"
374
+ ],
375
+ "execution_count": null,
376
+ "outputs": []
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "metadata": {},
381
+ "source": [
382
+ "print(\"Linear Regression Results\")\n",
383
+ "print(f\" Average MSE: {np.mean(mae):.4f}\")"
384
+ ],
385
+ "execution_count": null,
386
+ "outputs": []
387
+ },
388
+ {
389
+ "cell_type": "code",
390
+ "metadata": {},
391
+ "source": [
392
+ "# Task 1: Write your code here:\n",
393
+ "coeffs = {}\n",
394
+ "\n",
395
+ "coeffs['Lasso'] = model.coef_\n",
396
+ "coeffs['Ridge'] = model.coef_\n",
397
+ "\n",
398
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
399
+ "axes = axes.flatten()\n",
400
+ "features = X.columns\n",
401
+ "\n",
402
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
403
+ " # Sort features by absolute coefficient value\n",
404
+ " absolute_coef = np.abs(coef)\n",
405
+ " sorted_idx = np.argsort(absolute_coef)\n",
406
+ "\n",
407
+ " ax = axes[i]\n",
408
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
409
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
410
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
411
+ "\n",
412
+ "plt.tight_layout()\n",
413
+ "plt.show()"
414
+ ],
415
+ "execution_count": null,
416
+ "outputs": []
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "metadata": {},
421
+ "source": [
422
+ "# Task 2: Write your code here:\n",
423
+ "# Plot for Linear Regression Predictions vs. Ground Truth\n",
424
+ "plt.figure(figsize=(6, 4))\n",
425
+ "plt.scatter(y_test, y_pred, alpha=0.7)\n",
426
+ "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n",
427
+ "plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
428
+ "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n",
429
+ "plt.title(\"Predictions vs. Ground Truth\")\n",
430
+ "plt.grid(True)\n",
431
+ "\n",
432
+ "plt.tight_layout()\n",
433
+ "plt.show()"
434
+ ],
435
+ "execution_count": null,
436
+ "outputs": []
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "metadata": {},
441
+ "source": [
442
+ "# Task Bonus: Write your code here:"
443
+ ],
444
+ "execution_count": null,
445
+ "outputs": []
446
+ }
447
+ ],
448
+ "metadata": {
449
+ "kernelspec": {
450
+ "display_name": "Python 3",
451
+ "name": "python3"
452
+ },
453
+ "language_info": {
454
+ "name": "python"
455
+ }
456
+ },
457
+ "nbformat": 4,
458
+ "nbformat_minor": 0
459
+ }
submissions_extracted/384/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
+ "# transform to tensors so we can use the libarary\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
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
76
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
77
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
78
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
79
+ "\n"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# 2. Create TensorDataset objects\n",
89
+ "\n",
90
+ "train_dataset = TensorDataset(X_train, y_train)\n",
91
+ "test_dataset = TensorDataset(X_test, y_test)\n"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# 3. Create DataLoaders\n",
101
+ "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
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# 4. Print shape of one batch\n",
113
+ "first_sample, _ = train_dataset[0]\n",
114
+ "print(f\"Shape of one sample: {first_sample.shape}\")\n"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# 5. Display sample images\n",
124
+ "from torchvision.datasets import CIFAR10\n",
125
+ "from torchvision.transforms.functional import to_tensor\n",
126
+ "from torch.utils.data import DataLoader\n",
127
+ "import matplotlib.pyplot as plt\n",
128
+ "import torch.nn as nn\n",
129
+ "import torch.nn.functional as F\n",
130
+ "import torch\n",
131
+ "from torch.optim import AdamW\n",
132
+ "# Get one batch of images and labels\n",
133
+ "images, labels = next(iter(train_loader))\n",
134
+ "\n",
135
+ "# Display the first 6 images in the batch\n",
136
+ "plt.figure(figsize=(8, 4))\n",
137
+ "\n",
138
+ "for i in range(6):\n",
139
+ " plt.subplot(2, 3, i + 1)\n",
140
+ "\n",
141
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
142
+ " img = images[i].permute(1, 2, 0)\n",
143
+ "\n",
144
+ " plt.imshow(img)\n",
145
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
146
+ " plt.axis('off')\n",
147
+ "\n",
148
+ "plt.tight_layout()\n",
149
+ "plt.show()"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "class NN3Layer(nn.Module):\n",
159
+ " def __init__(self, input_dim, hidden_dim):\n",
160
+ " super(NN3Layer, self).__init__()\n",
161
+ "\n",
162
+ " # First linear layer: input features -> hidden layer\n",
163
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
164
+ "\n",
165
+ " # Second linear layer: hidden layer -> hidden layer\n",
166
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
167
+ "\n",
168
+ " # Output layer: hidden layer -> single continuous value\n",
169
+ " self.layer3 = nn.Linear(hidden_dim, 1)\n",
170
+ "\n",
171
+ " # ReLU activation for non-linearity in hidden layers\n",
172
+ " self.relu = nn.ReLU()\n",
173
+ "\n",
174
+ " # Defines how input data flows through the network\n",
175
+ " def forward(self, x):\n",
176
+ " # First hidden layer\n",
177
+ " a1 = self.relu(self.layer1(x))\n",
178
+ "\n",
179
+ " # Second hidden layer\n",
180
+ " a2 = self.relu(self.layer2(a1))\n",
181
+ "\n",
182
+ " # Output layer (regression output)\n",
183
+ " output = self.layer3(a2)\n",
184
+ "\n",
185
+ " return output"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 2: Write your training loop here:\n",
195
+ "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.view(-1, 1).to(device) # shape: (batch_size, num_features)\n",
204
+ " y_batch = y_batch.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
+ "# Device setup\n",
262
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
263
+ "# Hyperparameters (feel free to experiment!)\n",
264
+ "num_epochs = 20\n",
265
+ "learning_rate = 0.001\n",
266
+ "# Define criterion (loss function)\n",
267
+ "# Model parameters\n",
268
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
269
+ "hidden_dim = 64 # Design choice\n",
270
+ "\n",
271
+ "# Instantiate regression model\n",
272
+ "model = NN3Layer(input_dim, hidden_dim).to(device)\n",
273
+ "\n",
274
+ "# Print the model architecture\n",
275
+ "print(\"Model Architecture:\\n\")\n",
276
+ "print(model)\n",
277
+ "\n",
278
+ "# Calculate the total number of trainable parameters\n",
279
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
280
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
281
+ "criterion = nn.MSELoss()\n",
282
+ "# Define optimizer\n",
283
+ "optimizer = AdamW(model.parameters(), learning_rate)"
284
+ ],
285
+ "execution_count": null,
286
+ "outputs": []
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "metadata": {},
291
+ "source": [
292
+ "# Task 5: Start training for 20 epochs:\n",
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
+ "# Task 1: Write your code here:\n",
325
+ "# Plotting results\n",
326
+ "plt.figure(figsize=(7, 5))\n",
327
+ "\n",
328
+ "plt.plot(train_losses, label='Train Loss')\n",
329
+ "plt.plot(val_losses, label='Validation Loss')\n",
330
+ "plt.title('Loss over Epochs')\n",
331
+ "plt.xlabel('Epoch')\n",
332
+ "plt.ylabel('Loss (MSE)')\n",
333
+ "plt.legend()\n",
334
+ "\n",
335
+ "plt.tight_layout()\n",
336
+ "plt.show()"
337
+ ],
338
+ "execution_count": null,
339
+ "outputs": []
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "metadata": {},
344
+ "source": [
345
+ "# Task 2 (Bonus): Write your code here:\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/384/Q3.ipynb ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "# Task 1: Write your code here:\n",
29
+ "import pandas as pd\n",
30
+ "import numpy as np\n",
31
+ "import matplotlib.pyplot as plt\n",
32
+ "import seaborn as sns\n",
33
+ "import kagglehub\n",
34
+ "import os\n",
35
+ "from tqdm import tqdm\n",
36
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
37
+ "\n",
38
+ "df = pd.read_csv(csv_path)\n"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 2: Write your code here:\n",
48
+ "df.head()"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 3: Write your code here:\n",
58
+ "df.info()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# Task 4: Write your code here:\n",
68
+ "df.describe()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 1: Write your code here:\n",
78
+ "# 2. Do we have missing values?\n",
79
+ "def check_missing_values(df):\n",
80
+ " missing_values = df.isnull().sum()\n",
81
+ " print(\"Missing Values per Column:\")\n",
82
+ " print(missing_values[missing_values > 0])\n",
83
+ " if missing_values.any():\n",
84
+ " print(\"\\nHandle Missing Values as needed.\")\n",
85
+ " else:\n",
86
+ " print(\"\\nNo Missing Values Found.\")\n",
87
+ "\n",
88
+ "check_missing_values(df)"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "for i in range(189):\n",
98
+ " df[i] = df[i].fillna(df[i].mean())\n",
99
+ "\n",
100
+ "print(\"Missing values remaining:\", df.isnull().sum().sum())"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 2: Write your code here:\n",
110
+ "# 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
+ "from sklearn.preprocessing import LabelEncoder\n",
132
+ "# 3. Do we have categorical columns?\n",
133
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
134
+ "\n",
135
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
136
+ "label_encoders = {}\n",
137
+ "for col in categorical_cols:\n",
138
+ " le = LabelEncoder()\n",
139
+ " df[col] = le.fit_transform(df[col])\n",
140
+ " label_encoders[col] = le\n",
141
+ "\n",
142
+ "df"
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
+ "# Standardize features using StandardScaler\n",
153
+ "from sklearn.preprocessing import StandardScaler\n",
154
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])\n",
155
+ "scaler = StandardScaler()\n",
156
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
157
+ "df"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 5: Write your code here:\n",
167
+ "# 1. Is the target imbalanced?\n",
168
+ "def check_target_imbalance(df, target_column):\n",
169
+ " print(\"Target Distribution:\")\n",
170
+ "\n",
171
+ " df[target_column].hist() # Yeah you can just do this :)\n",
172
+ " plt.show()\n",
173
+ "\n",
174
+ "check_target_imbalance(df, \"Delivery_Time\")"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "pip install catboost"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "metadata": {},
191
+ "source": [
192
+ "# Import models\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 train_test_split\n",
200
+ "\n",
201
+ "models = CatBoostClassifier(\n",
202
+ " verbose=0,\n",
203
+ " n_estimators=320,\n",
204
+ " max_depth=4\n",
205
+ " )\n"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Import tree-based model for classification (Decision Tree Classifier)\n",
215
+ "from sklearn.tree import DecisionTreeClassifier\n",
216
+ "\n",
217
+ "# Use previously generated random classification data\n",
218
+ "X, y = df.copy(), df.copy()\n",
219
+ "\n",
220
+ "# Split ratio (80% train, 20% test)\n",
221
+ "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n",
222
+ "\n"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "n_splits = 5 # K\n",
232
+ "from sklearn.model_selection import StratifiedKFold\n",
233
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error,accuracy_score\n",
234
+ "\n",
235
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
236
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
237
+ ],
238
+ "execution_count": null,
239
+ "outputs": []
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "metadata": {},
244
+ "source": [
245
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
246
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
247
+ "\n",
248
+ " # 1. Split data\n",
249
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
250
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
251
+ "# Train Decision Tree Classifier\n",
252
+ " model = CatBoostClassifier(\n",
253
+ " verbose=0,\n",
254
+ " n_estimators=320,\n",
255
+ " max_depth=4) #\n",
256
+ " model.fit(X_train, y_train) # train\n",
257
+ " y_pred = model.predict(X_test) # validate\n",
258
+ "\n",
259
+ " # 3. Save metrics for that model in this fold\n",
260
+ " accuracy = accuracy_score(y_test, y_pred)\n",
261
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
262
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
263
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
264
+ "\n"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "metadata": {},
272
+ "source": [
273
+ "# Task 1: Write your code here:\n",
274
+ "coeffs = {}\n",
275
+ "\n",
276
+ "coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
277
+ "coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
278
+ "\n",
279
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
280
+ "axes = axes.flatten()\n",
281
+ "features = X.columns\n",
282
+ "\n",
283
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
284
+ " # Sort features by absolute coefficient value\n",
285
+ " absolute_coef = np.abs(coef)\n",
286
+ " sorted_idx = np.argsort(absolute_coef)\n",
287
+ "\n",
288
+ " ax = axes[i]\n",
289
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
290
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
291
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
292
+ "\n",
293
+ "plt.tight_layout()\n",
294
+ "plt.show()"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {},
302
+ "source": [
303
+ "# Task 2: Write your code here:"
304
+ ],
305
+ "execution_count": null,
306
+ "outputs": []
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "metadata": {},
311
+ "source": [
312
+ "# Task Bonus: Write your code here:"
313
+ ],
314
+ "execution_count": null,
315
+ "outputs": []
316
+ }
317
+ ],
318
+ "metadata": {
319
+ "kernelspec": {
320
+ "display_name": "Python 3",
321
+ "name": "python3"
322
+ },
323
+ "language_info": {
324
+ "name": "python"
325
+ }
326
+ },
327
+ "nbformat": 4,
328
+ "nbformat_minor": 0
329
+ }
submissions_extracted/385/Q1.ipynb ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
26
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
27
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n",
28
+ "from sklearn.ensemble import RandomForestClassifier\n",
29
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
30
+ "\n",
31
+ "import warnings\n",
32
+ "warnings.filterwarnings('ignore')\n",
33
+ "\n",
34
+ "\n",
35
+ "import seaborn as sns\n"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 1: Write your code here:\n",
45
+ "dataset = os.path.join(path, 'Q1_data.csv')\n",
46
+ "df = pd.read_csv(dataset)\n"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "df.head()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "df.info()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "df.describe()"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "plt.figure(figsize=(10, 5))\n",
83
+ "plt.hist(df['Delivery_Time'].dropna(), edgecolor='black')\n",
84
+ "plt.title('Graph')\n",
85
+ "plt.xlabel('Delivery Time')\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
+ "df = df.drop(columns=['Order_ID'])"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "cols = df.columns\n",
106
+ "df_clean = df[cols].copy()\n",
107
+ "df_clean = df_clean.dropna()"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "df_clean.info()"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "def check_duplicates(df):\n",
126
+ " duplicates = df.duplicated().sum()\n",
127
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
128
+ " if duplicates > 0:\n",
129
+ " print(\"Dropping Duplicates...\")\n",
130
+ " df.drop_duplicates(inplace=True)\n",
131
+ " print(\"Duplicates Dropped.\")\n",
132
+ " else:\n",
133
+ " print(\"No Duplicate Samples Found.\")\n",
134
+ "\n",
135
+ "check_duplicates(df_clean)"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "le = LabelEncoder()\n",
145
+ "cols = df_clean.select_dtypes(include='object').columns.to_list()\n",
146
+ "for i in cols:\n",
147
+ " df_clean[i] = le.fit_transform(df_clean[i])"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "X = df_clean.drop(columns = ['Delivery_Time'])\n",
157
+ "y = df_clean[\"Delivery_Time\"]"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "scaler = StandardScaler()\n",
167
+ "X = pd.DataFrame(scaler.fit_transform(X[X.columns]))"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [
176
+ "def check_target_imbalance(df, target_column):\n",
177
+ " print(\"Target Distribution:\")\n",
178
+ " print(df[target_column].value_counts(normalize=True))\n",
179
+ " sns.countplot(x=df[target_column])\n",
180
+ " plt.title(\"Target Distribution\")\n",
181
+ " plt.show()\n",
182
+ "\n",
183
+ "for i in df_clean.columns:\n",
184
+ " check_target_imbalance(df_clean, i)"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "from sklearn.model_selection import StratifiedKFold\n",
194
+ "\n",
195
+ "# Show full dataset class distribution\n",
196
+ "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n",
197
+ "print(\"Full Dataset Class Distribution\")\n",
198
+ "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n",
199
+ "print(\"-\" * 40)\n",
200
+ "\n",
201
+ "# Define Stratified K-Fold\n",
202
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
203
+ "\n",
204
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
205
+ "\n",
206
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
207
+ " # indexing for each fold\n",
208
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
209
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
210
+ "\n",
211
+ " print(f\"Fold {fold}\")\n",
212
+ " print(\" X_train shape:\", X_train.shape)\n",
213
+ " print(\" X_test shape :\", X_test.shape)\n",
214
+ " print(\" y_train shape:\", y_train.shape)\n",
215
+ " print(\" y_test shape :\", y_test.shape)\n",
216
+ "\n",
217
+ " # showing class distribution\n",
218
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
219
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
220
+ "\n",
221
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
222
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
223
+ "\n",
224
+ " print(\"-\" * 40)\n"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "from sklearn.ensemble import RandomForestRegressor\n",
234
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
235
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
236
+ "model.fit(X_train, y_train)\n",
237
+ "print(\"Model trained!\")"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "from sklearn.metrics import mean_absolute_error\n",
247
+ "y_pred = model.predict(X_test)\n",
248
+ "\n",
249
+ "mae = mean_absolute_error(y_test, y_pred)\n",
250
+ "\n",
251
+ "print(f\"MAE: {mae:,.2f}\")"
252
+ ],
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "# Task 1: Write your code here:"
261
+ ],
262
+ "execution_count": null,
263
+ "outputs": []
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "metadata": {},
268
+ "source": [
269
+ "# Task 2: Write your code here:"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "metadata": {},
277
+ "source": [
278
+ "# Task Bonus: Write your code here:"
279
+ ],
280
+ "execution_count": null,
281
+ "outputs": []
282
+ }
283
+ ],
284
+ "metadata": {
285
+ "kernelspec": {
286
+ "display_name": "Python 3",
287
+ "name": "python3"
288
+ },
289
+ "language_info": {
290
+ "name": "python"
291
+ }
292
+ },
293
+ "nbformat": 4,
294
+ "nbformat_minor": 0
295
+ }
submissions_extracted/385/Q2.ipynb ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "# PLEASE NOTE THAT I AM EXTREMELY SHORT ON TIME BECAUSE OF QUESTION 3 TOT"
8
+ ],
9
+ "execution_count": null,
10
+ "outputs": []
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "metadata": {},
15
+ "source": [
16
+ "import kagglehub\n",
17
+ "\n",
18
+ "# Download latest version\n",
19
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
20
+ "\n",
21
+ "print(\"Path to dataset files:\", path)"
22
+ ],
23
+ "execution_count": null,
24
+ "outputs": []
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "metadata": {},
29
+ "source": [
30
+ "import os\n",
31
+ "import pandas as pd\n",
32
+ "import numpy as np\n",
33
+ "from PIL import Image\n",
34
+ "from sklearn.model_selection import train_test_split\n",
35
+ "\n",
36
+ "# Load Labels\n",
37
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
38
+ "img_dir = os.path.join(path, \"images\")\n",
39
+ "\n",
40
+ "images = []\n",
41
+ "ages = []\n",
42
+ "\n",
43
+ "# Load Images and Resize\n",
44
+ "print(\"Loading images...\")\n",
45
+ "for index, row in labels_df.iterrows():\n",
46
+ " img_name = row.iloc[0]\n",
47
+ " age = row.iloc[1]\n",
48
+ " img_path = os.path.join(img_dir, img_name)\n",
49
+ "\n",
50
+ " if os.path.exists(img_path):\n",
51
+ " img = Image.open(img_path).convert('RGB')\n",
52
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
53
+ " images.append(img_array)\n",
54
+ " ages.append(age)\n",
55
+ "\n",
56
+ "X = np.array(images)\n",
57
+ "y = np.array(ages)\n",
58
+ "\n",
59
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
60
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
61
+ "\n",
62
+ "# Split Data\n",
63
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
64
+ "\n",
65
+ "print(f\"X_train shape: {X_train.shape}\")\n",
66
+ "print(f\"X_test shape: {X_test.shape}\")\n",
67
+ "print(f\"y_train shape: {y_train.shape}\")\n",
68
+ "print(f\"y_test shape: {y_test.shape}\")"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Import required libraries\n",
78
+ "import torch\n",
79
+ "import torch.nn as nn\n",
80
+ "from torch.optim import AdamW\n",
81
+ "import matplotlib.pyplot as plt\n",
82
+ "from torch.utils.data import DataLoader, TensorDataset\n",
83
+ "from sklearn.model_selection import train_test_split\n",
84
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
85
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
95
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
96
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
97
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
98
+ "y_test = torch.tensor(y_test, dtype=torch.float32)"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# 2. Create TensorDataset objects\n",
108
+ "train_dataset = TensorDataset(X_train, y_train)\n",
109
+ "test_dataset = TensorDataset(X_test, y_test)"
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)"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# 4. Print shape of one batch\n",
130
+ "X_batch, y_batch = next(iter(train_loader))\n",
131
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
132
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# 5. Display sample images\n",
142
+ "images, labels = next(iter(train_loader))\n",
143
+ "plt.figure(figsize=(8, 4))\n",
144
+ "for i in range(6):\n",
145
+ " plt.subplot(2, 3, i + 1)\n",
146
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
147
+ " img = images[i].permute(1, 2, 0)\n",
148
+ " plt.imshow(img)\n",
149
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
150
+ " plt.axis('off')\n",
151
+ "\n",
152
+ "plt.tight_layout()\n",
153
+ "plt.show()"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 1: Write your model class here:\n",
163
+ "class NN4Layer(nn.Module):\n",
164
+ " def __init__(self, input_dim, hidden_dim):\n",
165
+ " super(NN4Layer, self).__init__()\n",
166
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
167
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
168
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
169
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
170
+ " self.relu = nn.ReLU()\n",
171
+ "\n",
172
+ " def forward(self, x):\n",
173
+ " a1 = self.relu(self.layer1(x))\n",
174
+ " a2 = self.relu(self.layer2(a1))\n",
175
+ " a3 = self.relu(self.layer3(a2))\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
+ " model.train()\n",
190
+ "\n",
191
+ " running_loss = 0.0\n",
192
+ "\n",
193
+ " for X_batch, y_batch in train_loader:\n",
194
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
195
+ " y_batch = y_batch.to(device)\n",
196
+ "\n",
197
+ " outputs = model(X_batch)\n",
198
+ " loss = criterion(outputs, y_batch)\n",
199
+ "\n",
200
+ " optimizer.zero_grad()\n",
201
+ " loss.backward()\n",
202
+ " optimizer.step()\n",
203
+ "\n",
204
+ " running_loss += loss.item()\n",
205
+ " avg_loss = running_loss / len(train_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 3: Write your validation loop here:\n",
217
+ "def validate(model, criterion, test_loader, device):\n",
218
+ " model.eval()\n",
219
+ "\n",
220
+ " running_loss = 0.0\n",
221
+ "\n",
222
+ " with torch.no_grad():\n",
223
+ " for X_batch, y_batch in test_loader:\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
+ " outputs = model(X_batch)\n",
228
+ " loss = criterion(outputs, y_batch)\n",
229
+ "\n",
230
+ " running_loss += loss.item()\n",
231
+ "\n",
232
+ " avg_loss = running_loss / len(test_loader)\n",
233
+ "\n",
234
+ " return avg_loss"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Task 4: Define device, model, loss, optimizer:\n",
244
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
245
+ "\n",
246
+ "input_dim = 3 * 36 * 36\n",
247
+ "hidden_dim = 256\n",
248
+ "\n",
249
+ "# Instantiate regression model\n",
250
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
251
+ "\n",
252
+ "# Print the model architecture\n",
253
+ "print(\"Model Architecture:\\n\")\n",
254
+ "print(model)\n",
255
+ "\n",
256
+ "num_epochs = 20\n",
257
+ "learning_rate = 0.0001\n",
258
+ "\n",
259
+ "# Define criterion (loss function)\n",
260
+ "criterion = nn.MSELoss()\n",
261
+ "# Define optimizer\n",
262
+ "optimizer = AdamW(model.parameters(), learning_rate)"
263
+ ],
264
+ "execution_count": null,
265
+ "outputs": []
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "metadata": {},
270
+ "source": [
271
+ "# Task 5: Start training for 20 epochs:\n",
272
+ "\n",
273
+ "train_losses = []\n",
274
+ "val_losses = []\n",
275
+ "\n",
276
+ "print('Starting Training...')\n",
277
+ "for epoch in range(num_epochs):\n",
278
+ " # Train one epoch\n",
279
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
280
+ "\n",
281
+ " # Validate\n",
282
+ " val_loss = validate(model, criterion, test_loader, device)\n",
283
+ "\n",
284
+ " train_losses.append(train_loss)\n",
285
+ " val_losses.append(val_loss)\n",
286
+ "\n",
287
+ " if (epoch + 1) % 5 == 0:\n",
288
+ " print(\n",
289
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
290
+ " f'Train Loss: {train_loss:.4f}, '\n",
291
+ " f'Val Loss: {val_loss:.4f}'\n",
292
+ " )\n",
293
+ "\n",
294
+ "print('Training Complete!')"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {},
302
+ "source": [
303
+ "# Task 1: Write your code here:\n",
304
+ "plt.figure(figsize=(7, 5))\n",
305
+ "\n",
306
+ "plt.plot(train_losses, label='Train Loss')\n",
307
+ "plt.plot(val_losses, label='Validation Loss')\n",
308
+ "plt.title('Loss over Epochs')\n",
309
+ "plt.xlabel('Epoch')\n",
310
+ "plt.ylabel('Loss')\n",
311
+ "plt.legend()\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 (Bonus): Write your code here:"
324
+ ],
325
+ "execution_count": null,
326
+ "outputs": []
327
+ }
328
+ ],
329
+ "metadata": {
330
+ "kernelspec": {
331
+ "display_name": "Python 3",
332
+ "name": "python3"
333
+ },
334
+ "language_info": {
335
+ "name": "python"
336
+ }
337
+ },
338
+ "nbformat": 4,
339
+ "nbformat_minor": 0
340
+ }
submissions_extracted/385/Q3.ipynb ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "# Download latest version\n",
9
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
10
+ "print(\"Path to dataset files:\", path)"
11
+ ],
12
+ "execution_count": null,
13
+ "outputs": []
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "metadata": {},
18
+ "source": [
19
+ "%pip install catboost xgboost tqdm -q"
20
+ ],
21
+ "execution_count": null,
22
+ "outputs": []
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "source": [
28
+ "# Importing libraries\n",
29
+ "import pandas as pd\n",
30
+ "import numpy as np\n",
31
+ "# The Cat\n",
32
+ "from catboost import CatBoostClassifier, Pool\n",
33
+ "# sklearn stuff\n",
34
+ "from sklearn.model_selection import StratifiedKFold\n",
35
+ "from sklearn.metrics import f1_score, accuracy_score, classification_report, confusion_matrix, precision_score, recall_score\n",
36
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
37
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
38
+ "from sklearn.ensemble import RandomForestClassifier\n",
39
+ "# drawing and stuff\n",
40
+ "import matplotlib.pyplot as plt\n",
41
+ "# basic\n",
42
+ "import os\n",
43
+ "import warnings\n",
44
+ "warnings.filterwarnings('ignore')"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "metadata": {},
52
+ "source": [
53
+ "# Task 1: Write your code here:\n",
54
+ "path = os.path.join(path, 'Q3_data.csv')\n",
55
+ "data = pd.read_csv(path)"
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
+ "data.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
+ "data.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
+ "data.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
+ "\n",
96
+ "# I took numbers and categorical cols over here\n",
97
+ "numerical_cols = data.select_dtypes(include=[np.number]).columns\n",
98
+ "categorical_cols = data.select_dtypes(include=['object', 'category']).columns\n",
99
+ "\n",
100
+ "# replace empty numerical stuff with median in nums\n",
101
+ "for col in numerical_cols:\n",
102
+ " if data[col].isnull().sum() > 0:\n",
103
+ " data[col] = data[col].fillna(data[col].median())\n",
104
+ "\n",
105
+ "# categorical with mode\n",
106
+ "for col in categorical_cols:\n",
107
+ " if data[col].isnull().sum() > 0:\n",
108
+ " data[col] = data[col].fillna(data[col].mode()[0])"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {},
116
+ "source": [
117
+ "# Task 2: Write your code here:\n",
118
+ "initial_rows = len(data)\n",
119
+ "data = data.drop_duplicates()\n",
120
+ "removed = initial_rows - len(data)\n",
121
+ "print(f\"Dupes: {removed}\")"
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
+ "if len(categorical_cols) > 0:\n",
132
+ " data = pd.get_dummies(data, columns=categorical_cols.tolist(), drop_first=True)\n",
133
+ "else:\n",
134
+ " print(\"empty... O-O\")"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# Task 4: Write your code here:\n",
144
+ "if 'Target' in data.columns:\n",
145
+ " target = data['Target']\n",
146
+ " features = data.drop('Target', axis=1)\n",
147
+ " scaler = StandardScaler()\n",
148
+ " features_scaled = scaler.fit_transform(features)\n",
149
+ " data_scaled = pd.DataFrame(features_scaled, columns=features.columns)\n",
150
+ " data_scaled['Target'] = target.values\n",
151
+ "else:\n",
152
+ " scaler = StandardScaler()\n",
153
+ " data_scaled = pd.DataFrame(scaler.fit_transform(data), columns=data.columns)"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 5: Write your code here:\n",
163
+ "if 'Target' in data_scaled.columns:\n",
164
+ " target_counts = data_scaled['Target'].value_counts()\n",
165
+ " ratio = target_counts[0] / target_counts[1] if len(target_counts) > 1 else 0\n",
166
+ " print(f\"Class distribution: {dict(target_counts)}\")\n",
167
+ " print(f\"Ratio Class 0/Class 1: {ratio:.2f}\")\n",
168
+ " if ratio > 4 or ratio < 0.25:\n",
169
+ " print(\"Crazyyy imbalance\")\n",
170
+ " else:\n",
171
+ " print(\"Good to go!\")"
172
+ ],
173
+ "execution_count": null,
174
+ "outputs": []
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "metadata": {},
179
+ "source": [
180
+ "# Task 1: Write your code here:\n",
181
+ "X = data_scaled.drop('Target', axis=1)\n",
182
+ "y = data_scaled['Target']"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "# Task 2,3,4,5: Write your code here:\n",
192
+ "n_splits = 5\n",
193
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
194
+ "\n",
195
+ "# Storing our data\n",
196
+ "f1_scores = []\n",
197
+ "accuracy_scores = []\n",
198
+ "models = []\n",
199
+ "\n",
200
+ "# CatBoost parameters\n",
201
+ "catboost_params = {\n",
202
+ " 'iterations': 1000,\n",
203
+ " 'learning_rate': 0.05,\n",
204
+ " 'depth': 6,\n",
205
+ " 'l2_leaf_reg': 3,\n",
206
+ " 'border_count': 128,\n",
207
+ " 'loss_function': 'Logloss',\n",
208
+ " 'eval_metric': 'F1',\n",
209
+ " 'task_type': 'CPU',\n",
210
+ " 'random_seed': 42,\n",
211
+ " 'silent': True,\n",
212
+ " 'auto_class_weights': 'Balanced',\n",
213
+ " 'early_stopping_rounds': 50\n",
214
+ "}\n",
215
+ "\n",
216
+ "for fold, (train_idx, val_idx) in enumerate(skf.split(X, y), 1):\n",
217
+ "\n",
218
+ " # Split data\n",
219
+ " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
220
+ " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
221
+ "\n",
222
+ " print(f\"Train size: {len(X_train)} (Default: {y_train.sum()}, {y_train.mean()*100:.1f}%)\")\n",
223
+ " print(f\"Validation size: {len(X_val)} (Default: {y_val.sum()}, {y_val.mean()*100:.1f}%)\")\n",
224
+ "\n",
225
+ " # Creating CatBoost Pool objects\n",
226
+ " train_pool = Pool(X_train, y_train)\n",
227
+ " val_pool = Pool(X_val, y_val)\n",
228
+ "\n",
229
+ " # Train the CatBoost model\n",
230
+ " model = CatBoostClassifier(**catboost_params)\n",
231
+ " model.fit(train_pool, eval_set=val_pool, use_best_model=True, plot=False)\n",
232
+ "\n",
233
+ " # Make predictions\n",
234
+ " y_pred = model.predict(X_val)\n",
235
+ " y_pred_proba = model.predict_proba(X_val)[:, 1]\n",
236
+ "\n",
237
+ " # Calculate metrics\n",
238
+ " fold_f1 = f1_score(y_val, y_pred)\n",
239
+ " fold_accuracy = accuracy_score(y_val, y_pred)\n",
240
+ "\n",
241
+ " f1_scores.append(fold_f1)\n",
242
+ " accuracy_scores.append(fold_accuracy)\n",
243
+ " models.append(model)\n",
244
+ "\n",
245
+ " print(f\"F1 Score: {fold_f1:.4f}\")\n",
246
+ " print(f\"Accuracy: {fold_accuracy:.4f}\")\n",
247
+ "\n",
248
+ " # Additional metrics for better insight\n",
249
+ " fold_precision = precision_score(y_val, y_pred)\n",
250
+ " fold_recall = recall_score(y_val, y_pred)\n",
251
+ " print(f\"Precision: {fold_precision:.4f}\")\n",
252
+ " print(f\"Recall: {fold_recall:.4f}\")\n",
253
+ "\n",
254
+ "print(f\"Average F1 Score: {np.mean(f1_scores):.4f}\")\n",
255
+ "print(f\"Standard deviation: {np.std(f1_scores):.4f}\")\n",
256
+ "print(f\"Range: [{min(f1_scores):.4f}, {max(f1_scores):.4f}]\")\n",
257
+ "print(f\"Average Accuracy: {np.mean(accuracy_scores):.4f}\")\n",
258
+ "print(f\"Standard deviation: {np.std(accuracy_scores):.4f}\")"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# first collecting feature importance from all the models\n",
268
+ "feature_importances = []\n",
269
+ "for i, model in enumerate(models):\n",
270
+ " importances = model.get_feature_importance()\n",
271
+ " feature_importances.append(importances)\n",
272
+ "\n",
273
+ "# Average importance across them folds\n",
274
+ "avg_importances = np.mean(feature_importances, axis=0)\n",
275
+ "feature_importance_df = pd.DataFrame({\n",
276
+ " 'Feature': X.columns,\n",
277
+ " 'Importance': avg_importances\n",
278
+ "}).sort_values('Importance', ascending=False)\n",
279
+ "\n",
280
+ "# This is OUR GOLDEN FEATURE!!\n",
281
+ "golden_feature = feature_importance_df.iloc[0]\n",
282
+ "print(f\"The Golden Feature is: '{golden_feature}'\")"
283
+ ],
284
+ "execution_count": null,
285
+ "outputs": []
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "metadata": {},
290
+ "source": [
291
+ "# I HAVE NO TIME TOT !!"
292
+ ],
293
+ "execution_count": null,
294
+ "outputs": []
295
+ }
296
+ ],
297
+ "metadata": {
298
+ "kernelspec": {
299
+ "display_name": "Python 3",
300
+ "name": "python3"
301
+ },
302
+ "language_info": {
303
+ "name": "python"
304
+ }
305
+ },
306
+ "nbformat": 4,
307
+ "nbformat_minor": 0
308
+ }
submissions_extracted/386/Q1.ipynb ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "from sklearn.impute import SimpleImputer\n",
13
+ "\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
+ "food_delivery_path = os.path.join(path, 'Q1_data.csv')\n",
28
+ "df_food_delivery = pd.read_csv(food_delivery_path)"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "# Task 2: Write your code here:\n",
38
+ "df_food_delivery.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
+ "df_food_delivery.info()"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 4: Write your code here:\n",
58
+ "df_food_delivery.describe()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# Task 5: Write your code here:\n",
68
+ "# delivery_time distribution (target variable)\n",
69
+ "plt.figure(figsize=(10, 5))\n",
70
+ "plt.hist(df_food_delivery['Delivery_Time'].dropna(), bins=15, edgecolor='black')\n",
71
+ "plt.title('Delivery Time Distribution')\n",
72
+ "plt.xlabel('Delivery Time')\n",
73
+ "plt.ylabel('Frequency')\n",
74
+ "plt.show()"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 1: Write your code here:\n",
84
+ "df_food_delivery.drop(columns=['Order_ID'])"
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 values\n",
95
+ "print(\"Missing values:\")\n",
96
+ "print(df_food_delivery.isnull().sum())\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "num_cols = df_food_delivery.select_dtypes(include=['number']).columns\n",
106
+ "cat_cols = df_food_delivery.select_dtypes(include=['object', 'category']).columns\n",
107
+ "\n",
108
+ "num_imputer = SimpleImputer(strategy='median')\n",
109
+ "cat_imputer = SimpleImputer(strategy='most_frequent')\n",
110
+ "\n",
111
+ "# use .copy() to keep original df safe\n",
112
+ "df_clean = df_food_delivery.copy()\n",
113
+ "\n",
114
+ "# Fill Missing Values\n",
115
+ "df_clean[num_cols] = num_imputer.fit_transform(df_food_delivery[num_cols])\n",
116
+ "df_clean[cat_cols] = cat_imputer.fit_transform(df_food_delivery[cat_cols])\n",
117
+ "\n",
118
+ "print(f\"Missing values after cleaning: {df_clean.isnull().sum().sum()}\")\n",
119
+ "print(df_clean.isnull().sum())"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "from numpy._core.defchararray import index\n",
129
+ "# Task 3: Write your code here:\n",
130
+ "# Duplicate Check\n",
131
+ "\n",
132
+ "def check_duplicates(df):\n",
133
+ " duplicates = df.duplicated().sum()\n",
134
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
135
+ " if duplicates > 0:\n",
136
+ " print(\"Dropping Duplicates...\")\n",
137
+ " df.drop_duplicates(inplace=True)\n",
138
+ " print(\"Duplicates Dropped.\")\n",
139
+ " else:\n",
140
+ " print(\"No Duplicate Samples Found.\")\n",
141
+ "\n",
142
+ "check_duplicates(df_clean)"
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
+ "\n",
154
+ "print('data before encoding:\\n', cat_cols) #show before encoding\n",
155
+ "\n",
156
+ "onehot_encoder = OneHotEncoder(handle_unknown='ignore') # Instantiate OneHotEncoder\n",
157
+ "data_onehot_encoded = onehot_encoder.fit_transform() # Apply fit_transform to the copied\n",
158
+ "\n",
159
+ "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 5: Write your code here:\n",
169
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
170
+ "\n",
171
+ "print('data before scaling:\\n', df_clean) #show before scaling\n",
172
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
173
+ "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n",
174
+ "\n",
175
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task 6: Write your code here:\n",
185
+ "import seaborn as sns\n",
186
+ "\n",
187
+ "TARGET_COL = 'Delivery_Time'\n",
188
+ "\n",
189
+ "plt.figure(figsize=(8, 5))\n",
190
+ "if df_clean[TARGET_COL].dtype == 'object' or df_clean[TARGET_COL].nunique() < 10:\n",
191
+ " # Classification Problem\n",
192
+ " sns.countplot(x=TARGET_COL, data=df_clean, palette='viridis')\n",
193
+ " plt.title(f\"Target Distribution: {TARGET_COL} (Classification)\")\n",
194
+ " plt.ylabel(\"Count\")\n",
195
+ "else:\n",
196
+ " # Regression Problem\n",
197
+ " sns.histplot(df_clean[TARGET_COL], kde=True, color='blue')\n",
198
+ " plt.title(f\"Target Distribution: {TARGET_COL} (Regression)\")\n",
199
+ " plt.xlabel(\"Value\")\n",
200
+ "plt.show()\n",
201
+ "\n",
202
+ "# balanced"
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
+ "from sklearn.model_selection import train_test_split\n",
213
+ "\n",
214
+ "# --- 1. Separate Features (X) and Target (y) ---\n",
215
+ "X = df_clean.drop(columns=[TARGET_COL])\n",
216
+ "y = df_clean[TARGET_COL]\n",
217
+ "\n",
218
+ "# --- 2. Split Data ---\n",
219
+ "# Logic: If Classification -> Use Stratify. If Regression -> No Stratify.\n",
220
+ "is_classification = (y.dtype == 'object') or (y.nunique() < 20)\n",
221
+ "\n",
222
+ "if is_classification:\n",
223
+ " print(\"Detected Classification Task -> Using Stratified Split\")\n",
224
+ " X_train, X_test, y_train, y_test = train_test_split(\n",
225
+ " X, y, test_size=0.2, random_state=42, stratify=y\n",
226
+ " )\n",
227
+ "else:\n",
228
+ " print(\"Detected Regression Task -> Using Random Split\")\n",
229
+ " X_train, X_test, y_train, y_test = train_test_split(\n",
230
+ " X, y, test_size=0.2, random_state=42\n",
231
+ " )\n",
232
+ "\n",
233
+ "print(f\"Train Shape: {X_train.shape}\")\n",
234
+ "print(f\"Test Shape: {X_test.shape}\")\n",
235
+ "\n"
236
+ ],
237
+ "execution_count": null,
238
+ "outputs": []
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "metadata": {},
243
+ "source": [
244
+ "# Task 2,3,4,5: Write your code here:\n",
245
+ "from sklearn.ensemble import RandomForestRegressor\n",
246
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold\n",
247
+ "from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,\n",
248
+ " accuracy_score, precision_score, recall_score, f1_score,\n",
249
+ " classification_report, confusion_matrix)\n",
250
+ "\n",
251
+ "scaler = StandardScaler()\n",
252
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
253
+ "X_test_scaled = scaler.transform(X_test)\n",
254
+ "\n",
255
+ "model = {}\n",
256
+ "model['Random Forest'] = RandomForestRegressor(n_estimators=100, random_state=42)\n",
257
+ "\n",
258
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
259
+ "\n",
260
+ "mae_scores = []\n",
261
+ "rmse_scores = []\n",
262
+ "\n",
263
+ "for train_idx, val_idx in kfold.split(X_train_scaled):\n",
264
+ " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
265
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
266
+ "\n",
267
+ " # Train and predict\n",
268
+ " model.fit(X_fold_train, y_fold_train)\n",
269
+ " y_fold_pred = model.predict(X_fold_val)\n",
270
+ "\n",
271
+ " # Calculate metrics\n",
272
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
273
+ "\n",
274
+ "mae_scores = np.array(mae_scores)\n",
275
+ "\n",
276
+ "print(f\"5-Fold CV Results:\")\n",
277
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task 1: Write your code here:\n",
287
+ "importance = pd.DataFrame({\n",
288
+ " 'feature': num_cols + cat_cols,\n",
289
+ " 'importance': model.feature_importances_\n",
290
+ "}).sort_values('importance', ascending=False)\n",
291
+ "\n",
292
+ "plt.figure(figsize=(10, 6))\n",
293
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
294
+ "plt.xlabel('Importance')\n",
295
+ "plt.title('Feature Importance')\n",
296
+ "plt.gca().invert_yaxis()\n",
297
+ "plt.show()"
298
+ ],
299
+ "execution_count": null,
300
+ "outputs": []
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "metadata": {},
305
+ "source": [
306
+ "# Task 2: Write your code here:\n",
307
+ "\n",
308
+ "sns.histplot(df_clean['Delivery_Time'], kde=True, color='skyblue')\n",
309
+ "\n"
310
+ ],
311
+ "execution_count": null,
312
+ "outputs": []
313
+ },
314
+ {
315
+ "cell_type": "code",
316
+ "metadata": {},
317
+ "source": [
318
+ "# Task Bonus: Write your code here:"
319
+ ],
320
+ "execution_count": null,
321
+ "outputs": []
322
+ }
323
+ ],
324
+ "metadata": {
325
+ "kernelspec": {
326
+ "display_name": "Python 3",
327
+ "name": "python3"
328
+ },
329
+ "language_info": {
330
+ "name": "python"
331
+ }
332
+ },
333
+ "nbformat": 4,
334
+ "nbformat_minor": 0
335
+ }
submissions_extracted/386/Q2.ipynb ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:\n",
122
+ "class NN3Layer(nn.Module):\n",
123
+ "\n",
124
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
125
+ " super(NN3Layer, self).__init__()\n",
126
+ "\n",
127
+ " # First linear layer: input features -> hidden layer\n",
128
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
129
+ "\n",
130
+ " # Second linear layer: hidden layer -> hidden layer\n",
131
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
132
+ "\n",
133
+ " # Output layer: hidden layer -> number of classes (logits)\n",
134
+ " self.layer3 = nn.Linear(hidden_dim, output_dim)\n",
135
+ "\n",
136
+ " # ReLU activation for non-linearity\n",
137
+ " self.relu = nn.ReLU()\n",
138
+ "\n",
139
+ " # Defines how input data flows through the network\n",
140
+ " def forward(self, x):\n",
141
+ " # First hidden layer\n",
142
+ " z1 = self.layer1(x)\n",
143
+ " a1 = self.relu(z1)\n",
144
+ "\n",
145
+ " # Second hidden layer\n",
146
+ " z2 = self.layer2(a1)\n",
147
+ " a2 = self.relu(z2)\n",
148
+ "\n",
149
+ " # Output layer (raw scores / logits)\n",
150
+ " output = self.layer3(a2) # there is something missing here, remember? :)\n",
151
+ "\n",
152
+ " return output\n"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 2: Write your training loop here:\n",
162
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
163
+ " # Set the model to training mode\n",
164
+ " model.train()\n",
165
+ "\n",
166
+ " running_loss = 0.0\n",
167
+ "\n",
168
+ " for X_batch, y_batch in train_loader:\n",
169
+ " # Move batch to the selected device\n",
170
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
171
+ " y_batch = y_batch.to(device)\n",
172
+ "\n",
173
+ " # Forward pass\n",
174
+ " # TODO: make predictions\n",
175
+ " outputs = # <YOUR CODE HERE>\n",
176
+ " # TODO: compute loss\n",
177
+ " loss = # <YOUR CODE HERE>\n",
178
+ "\n",
179
+ " # Backward pass & optimization\n",
180
+ " optimizer.zero_grad() # Clear previous gradients\n",
181
+ " loss.backward() # Compute gradients\n",
182
+ " optimizer.step() # Update model parameters\n",
183
+ "\n",
184
+ " running_loss += loss.item()\n",
185
+ "\n",
186
+ " # Average loss over all batches\n",
187
+ " avg_loss = running_loss / len(train_loader)\n",
188
+ "\n",
189
+ " return avg_loss"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 3: Write your validation loop here:\n",
199
+ "def validate(model, criterion, test_loader, device):\n",
200
+ " # Set the model to evaluation mode\n",
201
+ " model.eval()\n",
202
+ "\n",
203
+ " running_loss = 0.0\n",
204
+ " correct = 0\n",
205
+ " total = 0\n",
206
+ "\n",
207
+ " with torch.no_grad():\n",
208
+ " for X_batch, y_batch in test_loader:\n",
209
+ " # Move data to device\n",
210
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
211
+ " y_batch = y_batch.to(device)\n",
212
+ "\n",
213
+ " # Forward pass\n",
214
+ " # TODO: make predictions\n",
215
+ " outputs = # <YOUR CODE HERE>\n",
216
+ " # TODO: compute loss\n",
217
+ " loss = # <YOUR CODE HERE>\n",
218
+ " running_loss += loss.item()\n",
219
+ "\n",
220
+ " # TODO: Apply Softmax to get probabilities\n",
221
+ " probabilities = F.softmax(# <YOUR CODE HERE>, dim=1)\n",
222
+ "\n",
223
+ " # TODO: Multiclass predictions\n",
224
+ " predicted = torch.argmax(# <YOUR CODE HERE>, dim=1)\n",
225
+ "\n",
226
+ " # Accuracy calculation\n",
227
+ " correct += (predicted == y_batch).sum().item()\n",
228
+ " total += y_batch.size(0)\n",
229
+ "\n",
230
+ " avg_loss = running_loss / len(test_loader)\n",
231
+ " # TODO: how do we calculate accuracy?\n",
232
+ " accuracy = # <YOUR CODE HERE>\n",
233
+ "\n",
234
+ " return avg_loss, accuracy\n"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Task 4: Define device, model, loss, optimizer:\n"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "metadata": {},
251
+ "source": [
252
+ "# Task 5: Start training for 20 epochs:\n"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 1: Write your code here:\n",
262
+ " Plotting results\n",
263
+ "plt.figure(figsize=(7, 5))\n",
264
+ "\n",
265
+ "plt.plot(train_losses, label='Train Loss')\n",
266
+ "plt.plot(val_losses, label='Validation Loss')\n",
267
+ "plt.title('Loss over Epochs')\n",
268
+ "plt.xlabel('Epoch')\n",
269
+ "plt.ylabel('Loss')\n",
270
+ "plt.legend()\n",
271
+ "\n",
272
+ "plt.tight_layout()\n",
273
+ "plt.show()"
274
+ ],
275
+ "execution_count": null,
276
+ "outputs": []
277
+ },
278
+ {
279
+ "cell_type": "code",
280
+ "metadata": {},
281
+ "source": [
282
+ "# Task 2 (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/386/Q3.ipynb ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "from sklearn.impute import SimpleImputer\n",
13
+ "\n",
14
+ "# Download latest version\n",
15
+ "\n",
16
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
17
+ "\n",
18
+ "\n",
19
+ "\n",
20
+ "print(\"Path to dataset files:\", path)"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "# Task 1: Write your code here:\n",
30
+ "Q3_data_path = os.path.join(path, 'Q3_data.csv')\n",
31
+ "df_Q3_data = pd.read_csv(Q3_data_path)"
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_Q3_data.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_Q3_data.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_Q3_data.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
+ "# Missing values\n",
72
+ "print(\"Missing values:\")\n",
73
+ "print(df_Q3_data.isnull().sum())\n",
74
+ "\n",
75
+ "num_cols = df_Q3_data.select_dtypes(include=['number']).columns\n",
76
+ "\n",
77
+ "num_imputer = SimpleImputer(strategy='median')\n",
78
+ "\n",
79
+ "# use .copy() to keep original df safe\n",
80
+ "df_clean = df_Q3_data.copy()\n",
81
+ "\n",
82
+ "# Fill Missing Values\n",
83
+ "df_clean[num_cols] = num_imputer.fit_transform(df_Q3_data[num_cols])\n",
84
+ "\n",
85
+ "print(f\"Missing values after cleaning: {df_clean.isnull().sum().sum()}\")\n",
86
+ "print(df_clean.isnull().sum())"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 2: Write your code here:\n",
96
+ "# Duplicate Check\n",
97
+ "\n",
98
+ "def check_duplicates(df):\n",
99
+ " duplicates = df.duplicated().sum()\n",
100
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
101
+ " if duplicates > 0:\n",
102
+ " print(\"Dropping Duplicates...\")\n",
103
+ " df.drop_duplicates(inplace=True)\n",
104
+ " print(\"Duplicates Dropped.\")\n",
105
+ " else:\n",
106
+ " print(\"No Duplicate Samples Found.\")\n",
107
+ "\n",
108
+ "check_duplicates(df_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
+ "# there are no categorical variables, there is no need"
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 #import StandardScaler\n",
129
+ "\n",
130
+ "print('data before scaling:\\n', df_Q3_data) #show before scaling\n",
131
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
132
+ "data_standard_scaled = standard_scaler.fit_transform(df_Q3_data) # Apply fit_transform\n",
133
+ "\n",
134
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
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
+ "import seaborn as sns\n",
145
+ "\n",
146
+ "TARGET_COL = 'Target'\n",
147
+ "\n",
148
+ "plt.figure(figsize=(8, 5))\n",
149
+ "if df_clean[TARGET_COL].dtype == 'object' or df_clean[TARGET_COL].nunique() < 10:\n",
150
+ " # Classification Problem\n",
151
+ " sns.countplot(x=TARGET_COL, data=df_clean, palette='viridis')\n",
152
+ " plt.title(f\"Target Distribution: {TARGET_COL} (Classification)\")\n",
153
+ " plt.ylabel(\"Count\")\n",
154
+ "else:\n",
155
+ " # Regression Problem\n",
156
+ " sns.histplot(df_clean[TARGET_COL], kde=True, color='blue')\n",
157
+ " plt.title(f\"Target Distribution: {TARGET_COL} (Regression)\")\n",
158
+ " plt.xlabel(\"Value\")\n",
159
+ "plt.show()"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your code here:\n",
169
+ "from sklearn.model_selection import train_test_split\n",
170
+ "\n",
171
+ "# --- 1. Separate Features (X) and Target (y) ---\n",
172
+ "X = df_Q3_data.drop(columns=[TARGET_COL])\n",
173
+ "y = df_Q3_data[TARGET_COL]\n",
174
+ "\n",
175
+ "# --- 2. Split Data ---\n",
176
+ "# Logic: If Classification -> Use Stratify. If Regression -> No Stratify.\n",
177
+ "is_classification = (y.dtype == 'object') or (y.nunique() < 20)\n",
178
+ "\n",
179
+ "if is_classification:\n",
180
+ " print(\"Detected Classification Task -> Using Stratified Split\")\n",
181
+ " X_train, X_test, y_train, y_test = train_test_split(\n",
182
+ " X, y, test_size=0.2, random_state=42, stratify=y\n",
183
+ " )\n",
184
+ "else:\n",
185
+ " print(\"Detected Regression Task -> Using Random Split\")\n",
186
+ " X_train, X_test, y_train, y_test = train_test_split(\n",
187
+ " X, y, test_size=0.2, random_state=42\n",
188
+ " )\n",
189
+ "\n",
190
+ "print(f\"Train Shape: {X_train.shape}\")\n",
191
+ "print(f\"Test Shape: {X_test.shape}\")\n"
192
+ ],
193
+ "execution_count": null,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "metadata": {},
199
+ "source": [
200
+ "# Task 2,3,4,5: Write your code here:\n",
201
+ "!pip install catboost\n",
202
+ "from catboost import CatBoostClassifier, CatBoostRegressor\n",
203
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold\n",
204
+ "from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,\n",
205
+ " accuracy_score, precision_score, recall_score, f1_score,\n",
206
+ " classification_report, confusion_matrix)\n",
207
+ "\n",
208
+ "scaler = StandardScaler()\n",
209
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
210
+ "X_test_scaled = scaler.transform(X_test)\n",
211
+ "\n",
212
+ "model = {}\n",
213
+ "model['CatBoost'] = CatBoostRegressor(verbose=0, random_state=42) # verbose=0 silences output\n",
214
+ "\n",
215
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
216
+ "\n",
217
+ "mae_scores = []\n",
218
+ "rmse_scores = []\n",
219
+ "\n",
220
+ "for train_idx, val_idx in kfold.split(X_train_scaled):\n",
221
+ " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
222
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
223
+ "\n",
224
+ " # Train and predict\n",
225
+ " model.fit(X_fold_train, y_fold_train)\n",
226
+ " y_fold_pred = model.predict(X_fold_val)\n",
227
+ "\n",
228
+ " # Calculate metrics\n",
229
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
230
+ "\n",
231
+ "mae_scores = np.array(mae_scores)\n",
232
+ "\n",
233
+ "print(f\"5-Fold CV Results:\")\n",
234
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Predictions and metrics\n",
244
+ "y_pred = model.predict(X_test_scaled)\n",
245
+ "\n",
246
+ "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n",
247
+ "print(classification_report(y_test, y_pred, target_names=['Target']))"
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
+ "\n",
258
+ "feature_importance = pd.DataFrame({\n",
259
+ " 'feature': feature_cols,\n",
260
+ " 'importance': model.feature_importances_\n",
261
+ "}).sort_values('importance', ascending=False)\n",
262
+ "\n",
263
+ "plt.figure(figsize=(10, 6))\n",
264
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
265
+ "plt.xlabel('Importance')\n",
266
+ "plt.title('Feature Importance')\n",
267
+ "plt.gca().invert_yaxis()\n",
268
+ "plt.show()"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Task 2: Write your code here:"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task Bonus: Write your code here:"
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/387/Q1.ipynb ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import kagglehub\n",
16
+ "\n",
17
+ "# Download latest version\n",
18
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
19
+ "\n",
20
+ "print(\"Path to dataset files:\", path)"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "# Task 1: Write your code here:\n",
30
+ "csv_path = \"<<<< From side bar \"\n",
31
+ "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 2: Write your code here:\n",
41
+ "df.head()"
42
+ ],
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# Task 3: Write your code here:\n",
51
+ "df.info()"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 4: Write your code here:\n",
61
+ "df.describe()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 5: Write your code here:\n",
71
+ "# Price distribution (target variable)\n",
72
+ "plt.figure(figsize=(10, 5))\n",
73
+ "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
74
+ "plt.title('Delivery_Time')\n",
75
+ "plt.xlabel('distance')\n",
76
+ "plt.ylabel('Time')\n",
77
+ "plt.show()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 1: Write your code here:\n",
87
+ "df_clean = df.drop(\"Order_ID\", axis = 1)\n",
88
+ "df_clean.info()"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# Task 2: Write your code here:\n",
98
+ "def check_missing_values(df):\n",
99
+ " missing_values = df.isnull().sum()\n",
100
+ " print(\"Missing Values per Column:\")\n",
101
+ " print(missing_values[missing_values > 0])\n",
102
+ " if missing_values.any():\n",
103
+ " print(\"\\nHandle Missing Values as needed.\")\n",
104
+ " else:\n",
105
+ " print(\"\\nNo Missing Values Found.\")\n",
106
+ "\n",
107
+ "check_missing_values(df_clean)"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# Task 3: Write your code here:\n",
117
+ "# 4. Do we have duplicate samples?\n",
118
+ "def check_duplicates(df):\n",
119
+ " duplicates = df.duplicated().sum()\n",
120
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
121
+ " if duplicates > 0:\n",
122
+ " print(\"Dropping Duplicates...\")\n",
123
+ " df.drop_duplicates(inplace=True)\n",
124
+ " print(\"Duplicates Dropped.\")\n",
125
+ " else:\n",
126
+ " print(\"No Duplicate Samples Found.\")\n",
127
+ "\n",
128
+ "check_duplicates(df_clean)"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 4: Write your code here:\n",
138
+ "# 3. Do we have categorical columns?\n",
139
+ "from sklearn.preprocessing import LabelEncoder\n",
140
+ "\n",
141
+ "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
142
+ "\n",
143
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
144
+ "\n",
145
+ "# Encoder\n",
146
+ "from sklearn.preprocessing import LabelEncoder\n",
147
+ "\n",
148
+ "label_encoders = {}\n",
149
+ "for col in categorical_cols:\n",
150
+ " le = LabelEncoder()\n",
151
+ " df_clean[col] = le.fit_transform(df_clean[col])\n",
152
+ " label_encoders[col] = le"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# to fill mode\n",
162
+ "def fill_with_mode(df, columns):\n",
163
+ " df_clean = df.copy()\n",
164
+ " for col in columns:\n",
165
+ " if col in df_clean.columns:\n",
166
+ " mode_value = df_clean[col].mode()\n",
167
+ " if len(mode_value) > 0:\n",
168
+ " df_clean[col] = df_clean[col].fillna(mode_value[0])\n",
169
+ " return df_clean\n",
170
+ "# Use\n",
171
+ "cols_to_fill_mode = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
172
+ "df_clean = fill_with_mode(df_clean, cols_to_fill_mode)\n",
173
+ "df_clean.info()\n",
174
+ "\n"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "def fill_with_mode(df, columns):\n",
184
+ " df_clean = df.copy()\n",
185
+ " for col in columns:\n",
186
+ " if col in df_clean.columns:\n",
187
+ " mode_value = df_clean[col].mode()\n",
188
+ " if len(mode_value) > 0:\n",
189
+ " df_clean[col] = df_clean[col].fillna(mode_value[0])\n",
190
+ " return df_clean\n",
191
+ "# Use\n",
192
+ "cols_to_fill_mode = ['Courier_Experience_yrs', 'Delivery_Time']\n",
193
+ "df_clean = fill_with_mode(df_clean, cols_to_fill_mode)\n",
194
+ "df_clean.info()"
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
+ "from sklearn.preprocessing import StandardScaler # can be StandardScaler\n",
205
+ "\n",
206
+ "features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
207
+ "\n",
208
+ "scaler = StandardScaler() # can be StandardScaler()\n",
209
+ "df_clean[features] = scaler.fit_transform(df_clean[features])"
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_distribution(df, target_column):\n",
220
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
221
+ "\n",
222
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
223
+ " plt.xlabel(target_column)\n",
224
+ " plt.ylabel(\"Frequency\")\n",
225
+ " plt.grid(False)\n",
226
+ "\n",
227
+ " plt.show()\n",
228
+ "\n",
229
+ "check_target_distribution(df_clean, 'Delivery_Time')"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "# Task 1: Write your code here:\n",
239
+ "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
240
+ "y = df_clean['Delivery_Time'].astype(float)\n",
241
+ "\n",
242
+ "from sklearn.model_selection import KFold\n",
243
+ "n_splits = 5 # K=5 Folds\n",
244
+ "# 5-Fold Cross-Validation, shuffled\n",
245
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
246
+ ],
247
+ "execution_count": null,
248
+ "outputs": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "metadata": {},
253
+ "source": [
254
+ "# Task 2,3,4,5: Write your code here:\n",
255
+ "from sklearn.ensemble import RandomForestRegressor\n",
256
+ "from sklearn.metrics import mean_absolute_error\n",
257
+ "\n",
258
+ "\n",
259
+ "model = RandomForestRegressor(n_estimators=200)\n",
260
+ "from sklearn.metrics import mean_absolute_error\n",
261
+ "\n",
262
+ "mae_results = []\n",
263
+ "\n",
264
+ "\n",
265
+ "\n",
266
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
267
+ "\n",
268
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
269
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
270
+ "\n",
271
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
272
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
273
+ "\n",
274
+ "\n",
275
+ " # Train\n",
276
+ " model.fit(X_train, y_train)\n",
277
+ "\n",
278
+ " # Predict\n",
279
+ " y_pred = model.predict(X_test)\n",
280
+ "\n",
281
+ " # Calculate metrics\n",
282
+ " mae = mean_absolute_error(y_test, y_pred)\n",
283
+ "\n",
284
+ " # Store results\n",
285
+ " mae_results.append(mae)\n",
286
+ " # all_results[model_name][\"rmse\"].append(rmse)\n",
287
+ "\n",
288
+ "print(f\" MAE: {np.mean(mae_results):.4f}\")\n",
289
+ "\n"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "metadata": {},
297
+ "source": [
298
+ "# Task 1: Write your code here:\n",
299
+ "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n",
300
+ " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
301
+ "\n",
302
+ "feature_importance = pd.DataFrame({\n",
303
+ " 'feature': feature_cols,\n",
304
+ " 'importance': model.feature_importances_\n",
305
+ "}).sort_values('importance', ascending=False)\n",
306
+ "\n",
307
+ "plt.figure(figsize=(10, 6))\n",
308
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
309
+ "plt.xlabel('Importance')\n",
310
+ "plt.title('Feature Importance')\n",
311
+ "plt.gca().invert_yaxis()\n",
312
+ "plt.show()"
313
+ ],
314
+ "execution_count": null,
315
+ "outputs": []
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "metadata": {},
320
+ "source": [
321
+ "# Task 2: Write your code here:\n",
322
+ "# Plot Predictions vs Ground Truth\n",
323
+ "plt.figure(figsize=(6, 4))\n",
324
+ "plt.scatter(y_test, y_pred, alpha=0.6)\n",
325
+ "plt.plot(\n",
326
+ " [y_test.min(), y_test.max()],\n",
327
+ " [y_test.min(), y_test.max()],\n",
328
+ " \"r--\",\n",
329
+ " linewidth=2\n",
330
+ ")\n",
331
+ "\n",
332
+ "plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n",
333
+ "plt.ylabel(\"Predicted Exam Scores\")\n",
334
+ "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n",
335
+ "plt.grid(True)\n",
336
+ "\n",
337
+ "plt.tight_layout()\n",
338
+ "plt.show()"
339
+ ],
340
+ "execution_count": null,
341
+ "outputs": []
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "metadata": {},
346
+ "source": [
347
+ "# Task Bonus: Write your code here:\n",
348
+ "from sklearn.tree import DecisionTreeRegressor\n",
349
+ "%pip install catboost\n",
350
+ "from catboost import CatBoostRegressor\n",
351
+ "\n",
352
+ "models = {\n",
353
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
354
+ " \"CatBoost\": CatBoostRegressor(verbose=0)\n",
355
+ "}\n",
356
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
357
+ "from sklearn.metrics import mean_absolute_error\n",
358
+ "\n",
359
+ "mae_results = []\n",
360
+ "# R train\n",
361
+ "# Storage for results\n",
362
+ "all_results = {}\n",
363
+ "\n",
364
+ "for name in models:\n",
365
+ " all_results[name] = {'mse': []}\n",
366
+ "\n",
367
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
368
+ "\n",
369
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
370
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
371
+ "\n",
372
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
373
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
374
+ "\n",
375
+ " for model_name, model in models.items():\n",
376
+ " print(f\"Training {model_name}...\")\n",
377
+ "\n",
378
+ " # Train\n",
379
+ " model.fit(X_train, y_train)\n",
380
+ "\n",
381
+ " # Predict\n",
382
+ " y_pred = model.predict(X_test)\n",
383
+ "\n",
384
+ " # Calculate metrics\n",
385
+ " mae = mean_absolute_error(y_test, y_pred)\n",
386
+ "\n",
387
+ " mae_results.append(mae)\n",
388
+ "\n",
389
+ "\n",
390
+ "print(f\" MAE: {np.mean(mae_results):.4f}\")\n"
391
+ ],
392
+ "execution_count": null,
393
+ "outputs": []
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "metadata": {},
398
+ "source": [],
399
+ "execution_count": null,
400
+ "outputs": []
401
+ }
402
+ ],
403
+ "metadata": {
404
+ "kernelspec": {
405
+ "display_name": "Python 3",
406
+ "name": "python3"
407
+ },
408
+ "language_info": {
409
+ "name": "python"
410
+ }
411
+ },
412
+ "nbformat": 4,
413
+ "nbformat_minor": 0
414
+ }
submissions_extracted/387/Q2.ipynb ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch\n",
11
+ "import torch.nn as nn\n",
12
+ "from torch.optim import AdamW\n",
13
+ "import matplotlib.pyplot as plt\n",
14
+ "from torch.utils.data import DataLoader, TensorDataset\n",
15
+ "from sklearn.model_selection import train_test_split\n",
16
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
17
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "import kagglehub\n",
27
+ "\n",
28
+ "# Download latest version\n",
29
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
30
+ "\n",
31
+ "print(\"Path to dataset files:\", path)"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "import os\n",
41
+ "import pandas as pd\n",
42
+ "import numpy as np\n",
43
+ "from PIL import Image\n",
44
+ "from sklearn.model_selection import train_test_split\n",
45
+ "\n",
46
+ "# Load Labels\n",
47
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
48
+ "img_dir = os.path.join(path, \"images\")\n",
49
+ "\n",
50
+ "images = []\n",
51
+ "ages = []\n",
52
+ "\n",
53
+ "# Load Images and Resize\n",
54
+ "print(\"Loading images...\")\n",
55
+ "for index, row in labels_df.iterrows():\n",
56
+ " img_name = row.iloc[0]\n",
57
+ " age = row.iloc[1]\n",
58
+ " img_path = os.path.join(img_dir, img_name)\n",
59
+ "\n",
60
+ " if os.path.exists(img_path):\n",
61
+ " img = Image.open(img_path).convert('RGB')\n",
62
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
63
+ " images.append(img_array)\n",
64
+ " ages.append(age)\n",
65
+ "\n",
66
+ "X = np.array(images)\n",
67
+ "y = np.array(ages)\n",
68
+ "\n",
69
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
70
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
71
+ "\n",
72
+ "# Split Data\n",
73
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
74
+ "\n",
75
+ "print(f\"X_train shape: {X_train.shape}\")\n",
76
+ "print(f\"X_test shape: {X_test.shape}\")\n",
77
+ "print(f\"y_train shape: {y_train.shape}\")\n",
78
+ "print(f\"y_test shape: {y_test.shape}\")"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
88
+ "import torch\n",
89
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
90
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
91
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
92
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
93
+ "\n"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# 2. Create TensorDataset objects\n",
103
+ "train_dataset = TensorDataset(X_train, y_train)\n",
104
+ "test_dataset = TensorDataset(X_test, y_test)\n",
105
+ "\n"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# 3. Create DataLoaders\n",
115
+ "\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
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# 4. Print shape of one batch\n",
128
+ "print(\"Train dataset:\", len(train_dataset))\n",
129
+ "print(\"Test dataset:\", len(test_dataset))\n"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Get the first batch from the training DataLoader\n",
139
+ "X_batch, y_batch = next(iter(train_loader))\n",
140
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
141
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# 5. Display sample images\n",
151
+ "\n",
152
+ "# Get one batch of images and labels\n",
153
+ "images, labels = next(iter(train_loader))\n",
154
+ "\n",
155
+ "# Display the first 6 images in the batch\n",
156
+ "plt.figure(figsize=(8, 4))\n",
157
+ "\n",
158
+ "for i in range(6):\n",
159
+ " plt.subplot(2, 3, i + 1)\n",
160
+ "\n",
161
+ " img = images[i].permute(1, 2, 0)\n",
162
+ " plt.imshow(img)\n",
163
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
164
+ " plt.axis('off')\n",
165
+ "plt.tight_layout()\n",
166
+ "plt.show()"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "class NN4Layer(nn.Module):\n",
176
+ " def __init__(self, input_dim, hidden_dim):\n",
177
+ " super(NN4Layer, self).__init__()\n",
178
+ "\n",
179
+ " # First linear layer: input features -> hidden layer\n",
180
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
181
+ "\n",
182
+ " # Second linear layer: hidden layer -> hidden layer\n",
183
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
184
+ "\n",
185
+ " # Third linear layer: hidden layer -> hidden layer\n",
186
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
187
+ "\n",
188
+ " # Output layer: hidden layer -> single continuous value\n",
189
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
190
+ "\n",
191
+ " # ReLU activation for non-linearity in hidden layers\n",
192
+ " self.relu = nn.ReLU()\n",
193
+ "\n",
194
+ " # Defines how input data flows through the network\n",
195
+ " def forward(self, x):\n",
196
+ " # First hidden layer\n",
197
+ " a1 = self.relu(self.layer1(x))\n",
198
+ "\n",
199
+ " # Second hidden layer\n",
200
+ " a2 = self.relu(self.layer2(a1))\n",
201
+ "\n",
202
+ " # Second hidden layer\n",
203
+ " a3 = self.relu(self.layer2(a2))\n",
204
+ "\n",
205
+ " # Output layer (regression output)\n",
206
+ " output = self.layer3(a3)\n",
207
+ "\n",
208
+ " return output"
209
+ ],
210
+ "execution_count": null,
211
+ "outputs": []
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "metadata": {},
216
+ "source": [
217
+ "# Task 2: Write your training loop here:\n",
218
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
219
+ " # Set the model to training mode\n",
220
+ " model.train()\n",
221
+ "\n",
222
+ " running_loss = 0.0\n",
223
+ "\n",
224
+ " for X_batch, y_batch in train_loader:\n",
225
+ " # Move batch to the selected device\n",
226
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
227
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
228
+ "\n",
229
+ " # Forward pass (continuous output)\n",
230
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
231
+ " loss = criterion(outputs, y_batch)\n",
232
+ "\n",
233
+ " # Backward pass & optimization\n",
234
+ " optimizer.zero_grad() # Clear previous gradients\n",
235
+ " loss.backward() # Compute gradients\n",
236
+ " optimizer.step() # Update model parameters\n",
237
+ "\n",
238
+ " running_loss += loss.item()\n",
239
+ "\n",
240
+ " # Average loss over all batches\n",
241
+ " avg_loss = running_loss / len(train_loader)\n",
242
+ "\n",
243
+ " return avg_loss"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "metadata": {},
251
+ "source": [
252
+ "# Task 3: Write your validation loop here:\n",
253
+ "\n",
254
+ "\n",
255
+ "def validate(model, criterion, test_loader, device):\n",
256
+ " # Set the model to evaluation mode\n",
257
+ " model.eval()\n",
258
+ "\n",
259
+ " running_loss = 0.0\n",
260
+ "\n",
261
+ " with torch.no_grad():\n",
262
+ " for X_batch, y_batch in test_loader:\n",
263
+ " # Move data to device\n",
264
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
265
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
266
+ "\n",
267
+ " # Forward pass (continuous output)\n",
268
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
269
+ " loss = criterion(outputs, y_batch)\n",
270
+ "\n",
271
+ " running_loss += loss.item()\n",
272
+ "\n",
273
+ " # Average loss over all batches\n",
274
+ " avg_loss = running_loss / len(test_loader)\n",
275
+ "\n",
276
+ " return avg_loss"
277
+ ],
278
+ "execution_count": null,
279
+ "outputs": []
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "metadata": {},
284
+ "source": [
285
+ "# Task 4: Define device, model, loss, optimizer:\n",
286
+ "# TODO: Set up the device (use GPU if available, otherwise CPU)\n",
287
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
288
+ "\n",
289
+ "input_dim = 3*36*36 # RGB and 32 * 32 size\n",
290
+ "hidden_dim = 15\n",
291
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
292
+ "\n",
293
+ "print(\"Model Architecture:\\n\")\n",
294
+ "print(model)\n",
295
+ "\n",
296
+ "# Calculate the total number of trainable parameters\n",
297
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
298
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "metadata": {},
306
+ "source": [
307
+ "# Define criterion (loss function)\n",
308
+ "criterion = nn.MSELoss()\n",
309
+ "# Hyperparameters (feel free to experiment!)\n",
310
+ "num_epochs = 20\n",
311
+ "learning_rate = 0.001\n",
312
+ "# Define optimizer\n",
313
+ "optimizer = AdamW(model.parameters(), learning_rate)"
314
+ ],
315
+ "execution_count": null,
316
+ "outputs": []
317
+ },
318
+ {
319
+ "cell_type": "code",
320
+ "metadata": {},
321
+ "source": [
322
+ "# Run Training\n",
323
+ "train_losses = []\n",
324
+ "val_losses = []\n",
325
+ "\n",
326
+ "print('Starting Training...')\n",
327
+ "for epoch in range(num_epochs):\n",
328
+ " # Train one epoch\n",
329
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
330
+ "\n",
331
+ " # Validate\n",
332
+ " val_loss = validate(model, criterion, test_loader, device)\n",
333
+ "\n",
334
+ " train_losses.append(train_loss)\n",
335
+ " val_losses.append(val_loss)\n",
336
+ "\n",
337
+ " if (epoch + 1) % 5 == 0:\n",
338
+ " print(\n",
339
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
340
+ " f'Train Loss: {train_loss:.4f}, '\n",
341
+ " f'Val Loss: {val_loss:.4f}'\n",
342
+ " )\n",
343
+ "\n",
344
+ "print('Training Complete!')"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "source": [
353
+ "# Task 1: Write your code here:\n",
354
+ "\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:\n",
376
+ "model.eval()\n",
377
+ "# Get one batch from the test DataLoader\n",
378
+ "images, labels = next(iter(test_loader))\n",
379
+ "# Move images to device\n",
380
+ "images = images.to(device)\n",
381
+ "labels = labels.to(device)\n",
382
+ "\n",
383
+ "with torch.no_grad():\n",
384
+ " # Flatten images before passing to the model\n",
385
+ " outputs = model(images.view(images.size(0), -1))\n",
386
+ " predictions = torch.argmax(outputs, dim=1)\n",
387
+ "\n",
388
+ "# Move tensors back to CPU for plotting\n",
389
+ "images = images.cpu()\n",
390
+ "labels = labels.cpu()\n",
391
+ "predictions = predictions.cpu()\n",
392
+ "\n",
393
+ "# Plot first 6 predictions\n",
394
+ "plt.figure(figsize=(8, 4))\n",
395
+ "for i in range(6):\n",
396
+ " plt.subplot(2, 3, i + 1)\n",
397
+ " plt.imshow(images[i].view(36,36), cmap='gray')\n",
398
+ " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
399
+ " plt.axis('off')\n",
400
+ "\n",
401
+ "plt.tight_layout()\n",
402
+ "plt.show()"
403
+ ],
404
+ "execution_count": null,
405
+ "outputs": []
406
+ },
407
+ {
408
+ "cell_type": "code",
409
+ "metadata": {},
410
+ "source": [],
411
+ "execution_count": null,
412
+ "outputs": []
413
+ }
414
+ ],
415
+ "metadata": {
416
+ "kernelspec": {
417
+ "display_name": "Python 3",
418
+ "name": "python3"
419
+ },
420
+ "language_info": {
421
+ "name": "python"
422
+ }
423
+ },
424
+ "nbformat": 4,
425
+ "nbformat_minor": 0
426
+ }
submissions_extracted/387/Q3.ipynb ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
14
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
15
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
16
+ "from sklearn.ensemble import RandomForestClassifier\n",
17
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
18
+ "\n",
19
+ "import warnings\n",
20
+ "warnings.filterwarnings('ignore')\n",
21
+ "\n",
22
+ "\n",
23
+ "# Download latest version\n",
24
+ "\n",
25
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
26
+ "\n",
27
+ "\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 CSV file\n",
40
+ "golden_feature_path = os.path.join(path, 'Q3_data.csv')\n",
41
+ "df = pd.read_csv(golden_feature_path)\n",
42
+ "\n",
43
+ "print(f\"Shape: {golden_feature.shape}\")"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Task 2: Write your code here:\n",
53
+ "df.head()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 3: Write your code here:\n",
63
+ "# Display dataset information using info()\n",
64
+ "df.info()\n"
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
+ "# Show statistical description using describe()\n",
75
+ "df.describe()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 1: Write your code here:\n",
85
+ "# Handle missing values appropriately\n",
86
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
87
+ "missing_data = pd.DataFrame({\n",
88
+ " 'Column': missing_percentage.index,\n",
89
+ " 'Missing_Percentage': missing_percentage.values\n",
90
+ "})\n",
91
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
92
+ "\n",
93
+ "print(\"Missing Data Analysis:\")\n",
94
+ "missing_data.head(26)\n",
95
+ "\n",
96
+ "print(\"Note that all over 50% fill with nan, my recmomdation is to drop the above columns list\")\n",
97
+ "df_clean=df.dropna(axis=1)\n",
98
+ "print(\"check after drop\")\n",
99
+ "# Task 1: Write your code here:\n",
100
+ "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n",
101
+ "missing_data = pd.DataFrame({\n",
102
+ " 'Column': missing_percentage.index,\n",
103
+ " 'Missing_Percentage': missing_percentage.values\n",
104
+ "})\n",
105
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
106
+ "\n",
107
+ "print(\"Missing Data Analysis:\")\n",
108
+ "missing_data.head(5)\n",
109
+ "print(\"empty list\")\n",
110
+ "print(df_clean.shape)\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
+ "# Check and remove duplicates if any exist\n",
123
+ "def check_duplicates(df):\n",
124
+ " duplicates = df.duplicated().sum()\n",
125
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
126
+ " if duplicates > 0:\n",
127
+ " print(\"Dropping Duplicates...\")\n",
128
+ " df.drop_duplicates(inplace=True)\n",
129
+ " print(\"Duplicates Dropped.\")\n",
130
+ " else:\n",
131
+ " print(\"No Duplicate Samples Found.\")\n",
132
+ "\n",
133
+ "check_duplicates(df_clean)"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 3: Write your code here:\n",
143
+ "# 3. Do we have categorical columns?\n",
144
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
145
+ "print(\"Do we have categorical columns?\")\n",
146
+ "print(\"Categorical Columns:\", list(categorical_cols))"
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
+ "# Pick only the numerical columns, NOT the target\n",
159
+ "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
160
+ "\n",
161
+ "scaler = StandardScaler()\n",
162
+ "\n",
163
+ "# scale the `numerical_cols`\n",
164
+ "df_clean[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
165
+ "df_clean.head()"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 5: Write your code here:\n",
175
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 5))\n",
176
+ "\n",
177
+ "# We use 'axes[0]' for the first slot\n",
178
+ "axes[0].hist(df_clean['Target'], bins=50, edgecolor='black', color='skyblue')\n",
179
+ "axes[0].set_title('Target Distribution (look imbalanced)')\n",
180
+ "axes[0].set_xlabel('Target')\n",
181
+ "axes[0].set_ylabel('Frequency')\n",
182
+ "\n",
183
+ "# We use 'axes[1]' for the second slot\n",
184
+ "axes[1].hist(df['P_2'], bins=50, edgecolor='black', color='salmon')\n",
185
+ "axes[1].set_title('P_2 Distribution')\n",
186
+ "axes[1].set_xlabel('P_2')\n",
187
+ "axes[1].set_ylabel('Frequency')\n",
188
+ "\n",
189
+ "# We use 'axes[2]' for the third slot\n",
190
+ "axes[2].hist(df['D_87'], bins=30, edgecolor='black', color='lightgreen')\n",
191
+ "axes[2].set_title('D_87 Distribution (almost all NAN)')\n",
192
+ "axes[2].set_xlabel('D_87')\n",
193
+ "axes[2].set_ylabel('Frequency')\n",
194
+ "\n",
195
+ "# 3. Final Layout Adjustment\n",
196
+ "plt.tight_layout() # This stops the titles from overlapping\n",
197
+ "plt.show()\n",
198
+ "print(\"Rule of thumb: If class distributions are not equal, then our data is imbalanced. \")"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "# Task 1: Write your code here:\n",
208
+ "X = df_clean.drop(\"Target\", axis=1).astype(float)\n",
209
+ "y = df_clean['Target'].astype(float)"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "# Task 2,3,4,5: Write your code here:\n",
219
+ "# Task 2,3,4,5: Write your code here:\n",
220
+ "n_splits = 5 # K=5 Folds\n",
221
+ "\n",
222
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
223
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
224
+ "\n",
225
+ "all_results = {}\n",
226
+ "\n",
227
+ "for name in sklearn_models:\n",
228
+ " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
229
+ "\n",
230
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
231
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
232
+ "\n",
233
+ " # 1. Split data\n",
234
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
235
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
236
+ "\n",
237
+ " # 2. Train & Validate sklearn models\n",
238
+ " for model_name, model in sklearn_models.items():\n",
239
+ " print(f\"Training {model_name}...\")\n",
240
+ " model.fit(X_train, y_train) # train\n",
241
+ " y_pred = model.predict(X_test) # validate\n",
242
+ "\n",
243
+ " # 3. Save metrics for that model in this fold\n",
244
+ " accuracy = accuracy_score(y_test, y_pred)\n",
245
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
246
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
247
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
248
+ "\n",
249
+ " all_results[model_name]['accuracy'].append(accuracy)\n",
250
+ " all_results[model_name]['precision'].append(precision)\n",
251
+ " all_results[model_name]['recall'].append(recall)\n",
252
+ " all_results[model_name]['f1'].append(f1)"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 1: Write your code here:\n",
262
+ "# i dind't know what i missed before!!\n",
263
+ "feature_cols = df_clean.drop(columns=['Target']).columns.tolist()\n",
264
+ "importance = pd.DataFrame({\n",
265
+ " 'feature': feature_cols,\n",
266
+ " 'importance': model.feature_importances_\n",
267
+ "}).sort_values('importance', ascending=False)\n",
268
+ "\n",
269
+ "plt.figure(figsize=(15, 15))\n",
270
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
271
+ "plt.xlabel('Importance')\n",
272
+ "plt.title('Feature Importance')\n",
273
+ "plt.gca().invert_yaxis()\n",
274
+ "plt.show()"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "# Task 2: Write your code here:"
284
+ ],
285
+ "execution_count": null,
286
+ "outputs": []
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "metadata": {},
291
+ "source": [
292
+ "# Task Bonus: Write your code here:"
293
+ ],
294
+ "execution_count": null,
295
+ "outputs": []
296
+ }
297
+ ],
298
+ "metadata": {
299
+ "kernelspec": {
300
+ "display_name": "Python 3",
301
+ "name": "python3"
302
+ },
303
+ "language_info": {
304
+ "name": "python"
305
+ }
306
+ },
307
+ "nbformat": 4,
308
+ "nbformat_minor": 0
309
+ }
submissions_extracted/388/Q1.ipynb ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import pandas as pd\n",
22
+ "import numpy as np\n",
23
+ "import matplotlib.pyplot as plt\n",
24
+ "import seaborn as sns\n",
25
+ "import kagglehub\n",
26
+ "import os\n",
27
+ "from tqdm import tqdm\n",
28
+ "\n",
29
+ "%matplotlib inline"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "# Task 1: Write your code here:\n",
39
+ "#Read the dataset Q1_data.csv using read_csv()\n",
40
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
41
+ "\n",
42
+ "df = pd.read_csv(csv_path)"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 2: Write your code here:\n",
52
+ "#Inspect the first few rows using head()\n",
53
+ "df.head()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 3: Write your code here:\n",
63
+ "#Display dataset information using info()\n",
64
+ "df.info()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 4: Write your code here:\n",
74
+ "#Show statistical description using describe()\n",
75
+ "df.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
+ "#Plot the target distribution (delivery_time)\n",
86
+ "\n",
87
+ "def check_target_distribution(df, target_column):\n",
88
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
89
+ "\n",
90
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
91
+ " plt.xlabel(target_column)\n",
92
+ " plt.ylabel(\"Frequency\")\n",
93
+ " plt.grid(False)\n",
94
+ "\n",
95
+ " plt.show()\n",
96
+ "\n",
97
+ "check_target_distribution(df, \"Delivery_Time\")"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 1: Write your code here:\n",
107
+ "#Drop the 'Order_ID' column from the data\n",
108
+ "\n",
109
+ "\n",
110
+ "\n",
111
+ "target_column = \"Order_ID\"\n",
112
+ "X = df.drop(target_column, axis=1)\n",
113
+ "y = df[target_column]\n",
114
+ "\n",
115
+ "df.columns.drop\n",
116
+ "\n",
117
+ "df.info()"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# Task 2: Write your code here:\n",
127
+ "#Handle missing values appropriately\n",
128
+ "#(Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
129
+ "\n",
130
+ "print(\"Missing values:\")\n",
131
+ "print(df.isnull().sum())"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "stat_cols = ['Distance_km', 'Vehicle_Type', 'Preparation_Time_min', \"Order_ID\"]\n",
141
+ "\n",
142
+ "df_clean = df.dropna(subset=stat_cols).copy()\n",
143
+ "print(f\"Shape after cleaning: {df_clean.shape}\")"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "# Task 3: Write your code here:\n",
153
+ "#Check and remove duplicates if any exist\n",
154
+ "\n",
155
+ "def check_duplicates(df):\n",
156
+ " duplicates = df.duplicated().sum()\n",
157
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
158
+ " if duplicates > 0:\n",
159
+ " print(\"Dropping Duplicates...\")\n",
160
+ " df.drop_duplicates(inplace=True)\n",
161
+ " print(\"Duplicates Dropped.\")\n",
162
+ " else:\n",
163
+ " print(\"No Duplicate Samples Found.\")\n",
164
+ "\n",
165
+ "check_duplicates(df)"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 4: Write your code here:\n",
175
+ "#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
176
+ "\n",
177
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
178
+ "\n",
179
+ "print('data before encoding:\\n', df) #show before encoding\n",
180
+ "\n",
181
+ "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
182
+ "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n",
183
+ "\n",
184
+ "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "# Task 5: Write your code here:\n",
194
+ "#Apply feature scaling for all features (Use StandardScaler)\n",
195
+ "\n",
196
+ "\n",
197
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
198
+ "\n",
199
+ "print('data before scaling:\\n', df) #show before scaling\n",
200
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
201
+ "df = standard_scaler.fit_transform(df) # Apply fit_transform\n",
202
+ "\n",
203
+ "print('\\nData after scaling:\\n', df) #show after scaling"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Task 6: Write your code here:\n",
213
+ "#Check for target imbalance and state\n",
214
+ "#if it is imbalanced or not (keep this cell empty if not needed)\n",
215
+ "\n",
216
+ "def check_target_imbalance(df, target_column):\n",
217
+ " print(\"Target Distribution:\")\n",
218
+ " print(df[target_column].value_counts(normalize=True))\n",
219
+ " sns.countplot(x=df[target_column])\n",
220
+ " plt.title(\"Target Distribution\")\n",
221
+ " plt.show()\n",
222
+ "\n",
223
+ "check_target_imbalance(df, \"Delivery_Time\")"
224
+ ],
225
+ "execution_count": null,
226
+ "outputs": []
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "metadata": {},
231
+ "source": [
232
+ "# Mean Squared Error in NumPy\n",
233
+ "def mean_squared_error(y, y_hat):\n",
234
+ " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
244
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
245
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
246
+ " losses = []\n",
247
+ "\n",
248
+ " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
249
+ " y_hat = np.dot(X, theta)\n",
250
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
251
+ " theta -= learning_rate * gradient\n",
252
+ "\n",
253
+ " loss = mean_squared_error(y, y_hat)\n",
254
+ " losses.append(loss)\n",
255
+ "\n",
256
+ " return theta, losses"
257
+ ],
258
+ "execution_count": null,
259
+ "outputs": []
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "metadata": {},
264
+ "source": [
265
+ "from sklearn.model_selection import KFold\n",
266
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "n_splits = 5 # K=5 Folds\n",
276
+ "\n",
277
+ "# 5-Fold Cross-Validation, shuffled\n",
278
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
279
+ ],
280
+ "execution_count": null,
281
+ "outputs": []
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "metadata": {},
286
+ "source": [
287
+ "# Storage for linear regression results for each fold\n",
288
+ "lr_losses = []\n",
289
+ "lr_mse = []\n",
290
+ "lr_rmse = []\n",
291
+ "lr_r2 = []"
292
+ ],
293
+ "execution_count": null,
294
+ "outputs": []
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "metadata": {},
299
+ "source": [
300
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
301
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
302
+ "\n",
303
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
304
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
305
+ "\n",
306
+ " # Train\n",
307
+ " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
308
+ "\n",
309
+ " # Validate\n",
310
+ " y_pred = np.dot(X_test.values, theta)\n",
311
+ "\n",
312
+ " # Calculate evaluation metrics\n",
313
+ " mse = sklearn_mse(y_test, y_pred)\n",
314
+ " rmse = np.sqrt(mse)\n",
315
+ " r2 = r2_score(y_test, y_pred)\n",
316
+ "\n",
317
+ " # Store results\n",
318
+ " lr_losses.append(losses)\n",
319
+ " lr_mse.append(mse)\n",
320
+ " lr_rmse.append(rmse)\n",
321
+ " lr_r2.append(r2)"
322
+ ],
323
+ "execution_count": null,
324
+ "outputs": []
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "metadata": {},
329
+ "source": [
330
+ "# Task 1: Write your code here:\n",
331
+ "#Split the dataset into features (X) and target (y)\n",
332
+ "\n",
333
+ "import numpy as np # for random data generation\n",
334
+ "\n",
335
+ "np.random.seed(42) # for reproducbility\n",
336
+ "\n",
337
+ "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n",
338
+ "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n",
339
+ "\n",
340
+ "\n",
341
+ "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n",
342
+ "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n"
343
+ ],
344
+ "execution_count": null,
345
+ "outputs": []
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "metadata": {},
350
+ "source": [
351
+ "# Task2\n",
352
+ "#Use the correct split: KFold OR StratifiedKFold\n",
353
+ "\n",
354
+ "from sklearn.model_selection import KFold\n",
355
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score"
356
+ ],
357
+ "execution_count": null,
358
+ "outputs": []
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "metadata": {},
363
+ "source": [
364
+ "# Task 4\n",
365
+ "\n",
366
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
367
+ "\n",
368
+ "print(\"Regression Metrics\\n\" + \"-\"*30)\n",
369
+ "\n",
370
+ "# Use previously generated random classification data\n",
371
+ "X, y = X_reg.copy(), y_reg.copy()\n",
372
+ "\n",
373
+ "# Split ratio (80% train, 20% test)\n",
374
+ "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n",
375
+ "\n",
376
+ "# Train a regression model\n",
377
+ "reg_model = LinearRegression()\n",
378
+ "reg_model.fit(X_train, y_train)\n",
379
+ "y_pred = reg_model.predict(X_test)\n",
380
+ "\n",
381
+ "# Calculate metrics\n",
382
+ "mae = mean_absolute_error(y_test, y_pred)\n",
383
+ "\n",
384
+ "print(\"MAE :\", mae)"
385
+ ],
386
+ "execution_count": null,
387
+ "outputs": []
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "metadata": {},
392
+ "source": [
393
+ "#Task 5\n",
394
+ "\n",
395
+ "average_losses = np.mean(lr_losses, axis=0)\n",
396
+ "\n",
397
+ "plt.figure(figsize=(10, 6))\n",
398
+ "plt.plot(average_losses, label='Average Loss')\n",
399
+ "plt.xlabel('Iteration')\n",
400
+ "plt.ylabel('MSE Loss')\n",
401
+ "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
402
+ "plt.legend()\n",
403
+ "plt.grid(True, alpha=0.3)\n",
404
+ "plt.show()"
405
+ ],
406
+ "execution_count": null,
407
+ "outputs": []
408
+ },
409
+ {
410
+ "cell_type": "code",
411
+ "metadata": {},
412
+ "source": [
413
+ "# Task 1: Write your code here:"
414
+ ],
415
+ "execution_count": null,
416
+ "outputs": []
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "metadata": {},
421
+ "source": [
422
+ "# Task 2: Write your code here:"
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
+ "cell_type": "code",
438
+ "metadata": {},
439
+ "source": [
440
+ "print(\"Evaluating models on the test set...\")\n",
441
+ "\n",
442
+ "# Dictionary to store performance metrics\n",
443
+ "model_performance = {}\n",
444
+ "\n",
445
+ "# Iterate through each trained model\n",
446
+ "for model_name, model in models.items():\n",
447
+ " print(f\"\\nEvaluating {model_name}...\")\n",
448
+ "\n",
449
+ " # Make predictions on the test set (hard labels)\n",
450
+ " y_pred = model.predict(X_test)\n",
451
+ "\n",
452
+ " # Calculate evaluation metrics\n",
453
+ " accuracy = accuracy_score(y_test, y_pred)\n",
454
+ " precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)\n",
455
+ " recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)\n",
456
+ " f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)\n",
457
+ "\n",
458
+ " # Store metrics\n",
459
+ " model_performance[model_name] = {\n",
460
+ " 'Accuracy': accuracy,\n",
461
+ " 'Precision': precision,\n",
462
+ " 'Recall': recall,\n",
463
+ " 'F1-Score': f1\n",
464
+ " }\n",
465
+ "\n",
466
+ " # Print metrics\n",
467
+ " print(f\" Accuracy: {accuracy:.4f}\")\n",
468
+ " print(f\" Precision: {precision:.4f}\")\n",
469
+ " print(f\" Recall: {recall:.4f}\")\n",
470
+ " print(f\" F1-Score: {f1:.4f}\")\n",
471
+ "\n",
472
+ " # Generate and visualize Confusion Matrix\n",
473
+ " cm = confusion_matrix(y_test, y_pred)\n",
474
+ " plt.figure(figsize=(6, 5))\n",
475
+ " sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,\n",
476
+ " xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)\n",
477
+ " plt.title(f'Confusion Matrix for {model_name}')\n",
478
+ " plt.xlabel('Predicted Label')\n",
479
+ " plt.ylabel('True Label')\n",
480
+ " plt.show()\n",
481
+ "\n",
482
+ "print(\"\\nAll models evaluated.\")"
483
+ ],
484
+ "execution_count": null,
485
+ "outputs": []
486
+ }
487
+ ],
488
+ "metadata": {
489
+ "kernelspec": {
490
+ "display_name": "Python 3",
491
+ "name": "python3"
492
+ },
493
+ "language_info": {
494
+ "name": "python"
495
+ }
496
+ },
497
+ "nbformat": 4,
498
+ "nbformat_minor": 0
499
+ }