File size: 8,811 Bytes
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
4b95eab
2c7f915
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
4b95eab
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
4b95eab
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
 
4b95eab
2c7f915
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
4b95eab
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
4b95eab
2c7f915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b95eab
2c7f915
 
 
 
4b95eab
 
2c7f915
 
 
4b95eab
 
 
 
 
 
 
 
 
 
2c7f915
 
 
4b95eab
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question 1 SOLUTION: Predict Food Delivery Time\n",
    "\n",
    "You are provided with a food delivery dataset that includes features such as delivery distance, restaurant preparation time, traffic conditions, and order details. Your objective is to develop a regression model that accurately predicts the delivery time in minutes.\n",
    "\n",
    "Your target is the column: \"delivery_time\".\n",
    "\n",
    "You are provided with the code to download and load the csv file.\n",
    "\n",
    "Your work will be evaluated based on the completion of the following tasks:\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 1: Read Data\n",
    "\n",
    "**Tasks:**\n",
    "\n",
    "1. Read the dataset using `read_csv()`\n",
    "2. Inspect the first few rows using `head()`\n",
    "3. Display dataset information using `info()`\n",
    "4. Show statistical description using `describe()`\n",
    "5. Plot the target distribution (delivery_time)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import kagglehub\n",
    "\n",
    "# Download latest version\n",
    "path = kagglehub.dataset_download(\"mohammad2012191/q1-ka-ai-2026\")\n",
    "\n",
    "print(\"Path to dataset files:\", path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "df = pd.read_csv(os.path.join(path, 'Q1_data.csv'))\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df['Delivery_Time'].hist(bins=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 2: Data Cleaning\n",
    "\n",
    "**Tasks:**\n",
    "\n",
    "Inspect and fix the following when needed:\n",
    "\n",
    "1. **Drop the 'Order_ID' column from the data** \n",
    "2. **Handle missing values appropriately** (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
    "3. **Check and remove duplicates** if any exist\n",
    "4. **Encode categorical variables** if needed\n",
    "5. **Apply feature scaling** to numerical features (Use StandardScaler)\n",
    "6. **Check for target imbalance and state if it is imbalanced or not** (keep this cell empty if not needed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 1\n",
    "df = df.drop('Order_ID', axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 2\n",
    "# Drop rows with missing target\n",
    "df = df.dropna(subset=['Delivery_Time'])\n",
    "# Fill missing values\n",
    "df = df.fillna(df.median(numeric_only=True))\n",
    "df = df.fillna(df.mode().iloc[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 3\n",
    "df = df.drop_duplicates()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 4\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "categorical_cols = df.select_dtypes(\"object\").columns\n",
    "for col in categorical_cols:\n",
    "    le = LabelEncoder()\n",
    "    df[col] = le.fit_transform(df[col])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 5\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "scaler = StandardScaler()\n",
    "X_cols = [col for col in df.columns if col != 'Delivery_Time']\n",
    "df[X_cols] = scaler.fit_transform(df[X_cols])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 6\n",
    "# Not applicable for regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 3: Modeling\n",
    "\n",
    "**Tasks:**\n",
    "\n",
    "1. Split the dataset into features (X) and target (y)\n",
    "2. Use the correct split: **KFold** OR **StratifiedKFold**\n",
    "3. Train a **RandomForest** model\n",
    "4. Evaluate using **MAE (Mean Absolute Error) ONLY**\n",
    "5. Print the averaged score across all folds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = df.drop('Delivery_Time', axis=1)\n",
    "y = df['Delivery_Time']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import KFold\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import mean_absolute_error\n",
    "import numpy as np\n",
    "\n",
    "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
    "model = RandomForestRegressor(random_state=42)\n",
    "scores = []\n",
    "\n",
    "for train_idx, val_idx in kf.split(X):\n",
    "    X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
    "    y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
    "    model.fit(X_train, y_train)\n",
    "    y_pred = model.predict(X_val)\n",
    "    scores.append(mean_absolute_error(y_val, y_pred))\n",
    "\n",
    "print(f'Average MAE: {np.mean(scores):.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 4: Plots\n",
    "\n",
    "**Tasks:**\n",
    "\n",
    "1. Plot feature importance from your trained model\n",
    "2. Plot predicted delivery time histogram"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "plt.barh(X.columns, model.feature_importances_)\n",
    "plt.xlabel('Importance')\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = model.predict(X)\n",
    "plt.hist(y_pred, bins=30)\n",
    "plt.xlabel('Predicted Delivery Time')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 5: Bonus - Ensemble\n",
    "\n",
    "**Task:**\n",
    "\n",
    "Why use one model? Let's use 2 then merge!\n",
    "\n",
    "Rewrite the KFold loop such that you:\n",
    "1. Train **2 different models** inside the loop at the same time in each iteration\n",
    "2. Average their predictions\n",
    "3. Calculate the MAE metric on the averaged predictions\n",
    "\n",
    "Use RandomForestRegressor and CatBoostRegressor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from catboost import CatBoostRegressor\n",
    "\n",
    "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
    "model1 = RandomForestRegressor(random_state=42)\n",
    "model2 = CatBoostRegressor(verbose=0, random_state=42)\n",
    "scores = []\n",
    "\n",
    "for train_idx, val_idx in kf.split(X):\n",
    "    X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
    "    y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
    "    \n",
    "    model1.fit(X_train, y_train)\n",
    "    model2.fit(X_train, y_train)\n",
    "    \n",
    "    y_pred1 = model1.predict(X_val)\n",
    "    y_pred2 = model2.predict(X_val)\n",
    "    y_pred_avg = (y_pred1 + y_pred2) / 2\n",
    "    \n",
    "    scores.append(mean_absolute_error(y_val, y_pred_avg))\n",
    "\n",
    "print(f'Average MAE (Ensemble): {np.mean(scores):.2f}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}