{ "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 }