Intro to AI Stage 2 practical exam: 1038 dual-graded students, rubric, solutions (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- submissions_extracted/696/Q3.ipynb +215 -0
- submissions_extracted/697/Q1.ipynb +390 -0
- submissions_extracted/697/Q3.ipynb +349 -0
- submissions_extracted/698/Q1.ipynb +438 -0
- submissions_extracted/698/Q2.ipynb +440 -0
- submissions_extracted/698/Q3.ipynb +410 -0
- submissions_extracted/699/Q1.ipynb +263 -0
- submissions_extracted/699/Q2.ipynb +383 -0
- submissions_extracted/699/Q3.ipynb +279 -0
- submissions_extracted/7/Q1.ipynb +259 -0
- submissions_extracted/70/Q1.ipynb +399 -0
- submissions_extracted/70/Q2.ipynb +334 -0
- submissions_extracted/70/Q3.ipynb +319 -0
- submissions_extracted/700/Q1.ipynb +263 -0
- submissions_extracted/700/Q2.ipynb +411 -0
- submissions_extracted/700/Q3.ipynb +258 -0
- submissions_extracted/701/Q1.ipynb +257 -0
- submissions_extracted/701/Q2.ipynb +398 -0
- submissions_extracted/701/Q3.ipynb +298 -0
- submissions_extracted/702/Q1.ipynb +317 -0
- submissions_extracted/702/Q2.ipynb +394 -0
- submissions_extracted/702/Q3.ipynb +272 -0
- submissions_extracted/703/Q1.ipynb +420 -0
- submissions_extracted/703/Q2.ipynb +426 -0
- submissions_extracted/703/Q3.ipynb +296 -0
- submissions_extracted/704/Q1.ipynb +340 -0
- submissions_extracted/704/Q2.ipynb +381 -0
- submissions_extracted/704/Q3.ipynb +179 -0
- submissions_extracted/705/Q1.ipynb +183 -0
- submissions_extracted/705/Q2.ipynb +192 -0
- submissions_extracted/705/Q3.ipynb +160 -0
- submissions_extracted/706/Q1.ipynb +438 -0
- submissions_extracted/706/Q2.ipynb +466 -0
- submissions_extracted/706/Q3.ipynb +351 -0
- submissions_extracted/707/Q1.ipynb +371 -0
- submissions_extracted/707/Q2.ipynb +406 -0
- submissions_extracted/707/Q3.ipynb +333 -0
- submissions_extracted/708/Q1.ipynb +308 -0
- submissions_extracted/708/Q2.ipynb +374 -0
- submissions_extracted/708/Q3.ipynb +240 -0
- submissions_extracted/709/Q1.ipynb +326 -0
- submissions_extracted/709/Q2.ipynb +341 -0
- submissions_extracted/709/Q3.ipynb +280 -0
- submissions_extracted/71/Q1.ipynb +208 -0
- submissions_extracted/71/Q2.ipynb +231 -0
- submissions_extracted/71/Q3.ipynb +170 -0
- submissions_extracted/710/Q1.ipynb +292 -0
- submissions_extracted/710/Q2.ipynb +376 -0
- submissions_extracted/710/Q3.ipynb +287 -0
- submissions_extracted/711/Q1.ipynb +339 -0
submissions_extracted/696/Q3.ipynb
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"import numpy as np\n",
|
| 27 |
+
"import pandas as pd\n",
|
| 28 |
+
"import matplotlib.pyplot as plt\n",
|
| 29 |
+
"import os\n",
|
| 30 |
+
"import kagglehub\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 33 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 34 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 35 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"import warnings\n",
|
| 38 |
+
"warnings.filterwarnings('ignore')"
|
| 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 |
+
"# Load the dataset\n",
|
| 49 |
+
"Golden_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 50 |
+
"df_Golden = pd.read_csv(Golden_path)\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"print(f\"Dataset shape: {df_Golden.shape}\")"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 2: Write your code here:\n",
|
| 62 |
+
"df_Golden.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 |
+
"df_Golden.info()"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 4: Write your code here:\n",
|
| 82 |
+
"df_Golden.describe()"
|
| 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 |
+
"print(\"Missing values:\")\n",
|
| 93 |
+
"print(df_Golden.isnull().sum())"
|
| 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_duplicates(df_Golden):\n",
|
| 104 |
+
" duplicates = df_Golden.duplicated().sum()\n",
|
| 105 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 106 |
+
" if duplicates > 0:\n",
|
| 107 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 108 |
+
" df_Golden.drop_duplicates(inplace=True)\n",
|
| 109 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 110 |
+
" else:\n",
|
| 111 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"check_duplicates(df_Golden)"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# Task 3: Write your code here:\n",
|
| 123 |
+
"# dtypes: float64(148), int64(41) so no need"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# Task 4: Write your code here:\n",
|
| 133 |
+
"# Define features (X) and target (y)\n",
|
| 134 |
+
"numerical_cols = df_Golden.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"scaler = StandardScaler()\n",
|
| 137 |
+
"df_Golden[numerical_cols] = scaler.fit_transform(df_Golden[numerical_cols])\n",
|
| 138 |
+
"df_Golden.head()"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 5: Write your code here:\n",
|
| 148 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 149 |
+
"plt.hist(['Target'].dropna(), bins=50, edgecolor='black')\n",
|
| 150 |
+
"plt.title('Target Distribution')\n",
|
| 151 |
+
"plt.xlabel('Target')\n",
|
| 152 |
+
"plt.ylabel('Frequency')\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 code here:"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 1: Write your code here:"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"# Task 2: Write your code here:"
|
| 190 |
+
],
|
| 191 |
+
"execution_count": null,
|
| 192 |
+
"outputs": []
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"source": [
|
| 198 |
+
"# Task Bonus: Write your code here:"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
}
|
| 203 |
+
],
|
| 204 |
+
"metadata": {
|
| 205 |
+
"kernelspec": {
|
| 206 |
+
"display_name": "Python 3",
|
| 207 |
+
"name": "python3"
|
| 208 |
+
},
|
| 209 |
+
"language_info": {
|
| 210 |
+
"name": "python"
|
| 211 |
+
}
|
| 212 |
+
},
|
| 213 |
+
"nbformat": 4,
|
| 214 |
+
"nbformat_minor": 0
|
| 215 |
+
}
|
submissions_extracted/697/Q1.ipynb
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"csv_path = os.path.join(path,\"Q1_data.csv\")\n",
|
| 22 |
+
"df = pd.read_csv(csv_path)"
|
| 23 |
+
],
|
| 24 |
+
"execution_count": null,
|
| 25 |
+
"outputs": []
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"df.head()"
|
| 32 |
+
],
|
| 33 |
+
"execution_count": null,
|
| 34 |
+
"outputs": []
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"source": [
|
| 40 |
+
"df.info()"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"df.describe()"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# 1. What does our target variable (charges) look like?\n",
|
| 59 |
+
"def check_target_distribution(df, Delivery_Time):\n",
|
| 60 |
+
" df[Delivery_Time].hist(bins=30, edgecolor='black')\n",
|
| 61 |
+
"\n",
|
| 62 |
+
" plt.title(f\"Target Distribution ({Delivery_Time})\")\n",
|
| 63 |
+
" plt.xlabel(Delivery_Time)\n",
|
| 64 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 65 |
+
" plt.grid(False)\n",
|
| 66 |
+
"\n",
|
| 67 |
+
" plt.show()\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"from sklearn.preprocessing import MinMaxScaler\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"features = df.columns.drop(\"Order_ID\")\n"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# 2. Do we have missing values?\n",
|
| 90 |
+
"def check_missing_values(df):\n",
|
| 91 |
+
" missing_values = df.isnull().sum()\n",
|
| 92 |
+
" print(\"Missing Values per Column:\")\n",
|
| 93 |
+
" print(missing_values[missing_values > 0])\n",
|
| 94 |
+
" if missing_values.any():\n",
|
| 95 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 96 |
+
" else:\n",
|
| 97 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"check_missing_values(df)"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# 4. Do we have duplicate samples?\n",
|
| 116 |
+
"def check_duplicates(df):\n",
|
| 117 |
+
" duplicates = df.duplicated().sum()\n",
|
| 118 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 119 |
+
" if duplicates > 0:\n",
|
| 120 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 121 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 122 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 123 |
+
" else:\n",
|
| 124 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"check_duplicates(df)"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# 3. Do we have categorical columns?\n",
|
| 136 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Encode categorical columns - converts text to integers\n",
|
| 148 |
+
"for col in categorical_cols:\n",
|
| 149 |
+
" le = LabelEncoder()\n",
|
| 150 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"df.head()"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"df.describe()"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"from sklearn.preprocessing import MinMaxScaler\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"scaler = MinMaxScaler()\n",
|
| 175 |
+
"df[features] = scaler.fit_transform(df[numerical_cols])\n",
|
| 176 |
+
"df.head()"
|
| 177 |
+
],
|
| 178 |
+
"execution_count": null,
|
| 179 |
+
"outputs": []
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [
|
| 185 |
+
"# 1. Is the target imbalanced?\n",
|
| 186 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 187 |
+
" print(\"Target Distribution:\")\n",
|
| 188 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 189 |
+
" sns.countplot(x=df[target_column])\n",
|
| 190 |
+
" plt.title(\"Target Distribution\")\n",
|
| 191 |
+
" plt.show()\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"check_target_imbalance(df, \"Delivery_Time\")"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 203 |
+
"from sklearn.svm import SVR\n",
|
| 204 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 205 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 206 |
+
"from lightgbm import LGBMRegressor\n",
|
| 207 |
+
"from catboost import CatBoostRegressor"
|
| 208 |
+
],
|
| 209 |
+
"execution_count": null,
|
| 210 |
+
"outputs": []
|
| 211 |
+
},
|
| 212 |
+
{
|
| 213 |
+
"cell_type": "code",
|
| 214 |
+
"metadata": {},
|
| 215 |
+
"source": [
|
| 216 |
+
"X = df.drop(\"Delivery_Time\", axis=1)\n",
|
| 217 |
+
"y = df['Delivery_Time']"
|
| 218 |
+
],
|
| 219 |
+
"execution_count": null,
|
| 220 |
+
"outputs": []
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "code",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"source": [
|
| 226 |
+
"from sklearn.model_selection import KFold\n",
|
| 227 |
+
"from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 239 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 240 |
+
],
|
| 241 |
+
"execution_count": null,
|
| 242 |
+
"outputs": []
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"cell_type": "code",
|
| 246 |
+
"metadata": {},
|
| 247 |
+
"source": [
|
| 248 |
+
"# Storage for linear regression results for each fold\n",
|
| 249 |
+
"lr_losses = []\n",
|
| 250 |
+
"lr_mse = []\n",
|
| 251 |
+
"lr_rmse = []\n",
|
| 252 |
+
"lr_r2 = []"
|
| 253 |
+
],
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"outputs": []
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"metadata": {},
|
| 260 |
+
"source": [
|
| 261 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 262 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 265 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"\n"
|
| 269 |
+
],
|
| 270 |
+
"execution_count": null,
|
| 271 |
+
"outputs": []
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"cell_type": "code",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"source": [
|
| 277 |
+
"sklearn_models = {\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" \"Random Forest\": RandomForestRegressor(\n",
|
| 280 |
+
" n_estimators=320, # Number of trees\n",
|
| 281 |
+
" max_depth=4\n",
|
| 282 |
+
" ),\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"}"
|
| 285 |
+
],
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"outputs": []
|
| 288 |
+
},
|
| 289 |
+
{
|
| 290 |
+
"cell_type": "code",
|
| 291 |
+
"metadata": {},
|
| 292 |
+
"source": [
|
| 293 |
+
"all_results = {}\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"for name in sklearn_models:\n",
|
| 296 |
+
" all_results[name] = {'mae': []}"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"average_losses = np.mean(lr_losses, axis=0)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 308 |
+
"plt.plot(average_losses, label='Average Loss')\n",
|
| 309 |
+
"plt.xlabel('Iteration')\n",
|
| 310 |
+
"plt.ylabel('MAE Loss')\n",
|
| 311 |
+
"plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
|
| 312 |
+
"plt.legend()\n",
|
| 313 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 314 |
+
"plt.show()"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 324 |
+
"importances = {}\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
|
| 327 |
+
"importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n",
|
| 328 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"# Create a 1x3 plot\n",
|
| 331 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 332 |
+
"axes = axes.flatten()\n",
|
| 333 |
+
"features = X.columns\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 336 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 337 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" ax = axes[i]\n",
|
| 340 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 341 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 342 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"plt.tight_layout()\n",
|
| 345 |
+
"plt.show()"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
},
|
| 350 |
+
{
|
| 351 |
+
"cell_type": "code",
|
| 352 |
+
"metadata": {},
|
| 353 |
+
"source": [
|
| 354 |
+
" Calculate the baseline predictions (mean of the target)\n",
|
| 355 |
+
"baseline_pred = np.full_like(y, y.mean())\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"# Evaluate the baseline\n",
|
| 358 |
+
"baseline_mse = sklearn_mse(y, baseline_pred)\n",
|
| 359 |
+
"baseline_rmse = np.sqrt(baseline_mse)\n",
|
| 360 |
+
"baseline_r2 = r2_score(y, baseline_pred)\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"print(f\"Baseline MSE (using mean target): {baseline_mse:.4f}\")\n",
|
| 363 |
+
"print(f\"Baseline RMSE (using mean target): {baseline_rmse:.4f}\")\n",
|
| 364 |
+
"print(f\"Baseline R2 (using mean target): {baseline_r2:.4f}\")"
|
| 365 |
+
],
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"outputs": []
|
| 368 |
+
},
|
| 369 |
+
{
|
| 370 |
+
"cell_type": "code",
|
| 371 |
+
"metadata": {},
|
| 372 |
+
"source": [
|
| 373 |
+
"# Task Bonus: Write your code here:"
|
| 374 |
+
],
|
| 375 |
+
"execution_count": null,
|
| 376 |
+
"outputs": []
|
| 377 |
+
}
|
| 378 |
+
],
|
| 379 |
+
"metadata": {
|
| 380 |
+
"kernelspec": {
|
| 381 |
+
"display_name": "Python 3",
|
| 382 |
+
"name": "python3"
|
| 383 |
+
},
|
| 384 |
+
"language_info": {
|
| 385 |
+
"name": "python"
|
| 386 |
+
}
|
| 387 |
+
},
|
| 388 |
+
"nbformat": 4,
|
| 389 |
+
"nbformat_minor": 0
|
| 390 |
+
}
|
submissions_extracted/697/Q3.ipynb
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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[
|
| 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 |
+
"\n",
|
| 11 |
+
"clear_output()"
|
| 12 |
+
],
|
| 13 |
+
"execution_count": null,
|
| 14 |
+
"outputs": []
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "code",
|
| 18 |
+
"metadata": {},
|
| 19 |
+
"source": [
|
| 20 |
+
"import pandas as pd\n",
|
| 21 |
+
"import numpy as np\n",
|
| 22 |
+
"import matplotlib.pyplot as plt\n",
|
| 23 |
+
"import seaborn as sns\n",
|
| 24 |
+
"import kagglehub\n",
|
| 25 |
+
"import os\n",
|
| 26 |
+
"from tqdm import tqdm\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"%matplotlib inline"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"import kagglehub\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"# Download latest version\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"print(\"Path to dataset files:\", path)"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\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 |
+
"df.head()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"df.info()"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"df.describe()"
|
| 85 |
+
],
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": []
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"source": [
|
| 93 |
+
"def check_missing_values(df):\n",
|
| 94 |
+
" missing_values = df.isnull().sum()\n",
|
| 95 |
+
" print(\"Missing Values per Column:\")\n",
|
| 96 |
+
" print(missing_values[missing_values > 0])\n",
|
| 97 |
+
" if missing_values.any():\n",
|
| 98 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 99 |
+
" else:\n",
|
| 100 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"check_missing_values(df)"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"#put missing"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"\n",
|
| 121 |
+
"def check_duplicates(df):\n",
|
| 122 |
+
" duplicates = df.duplicated().sum()\n",
|
| 123 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 124 |
+
" if duplicates > 0:\n",
|
| 125 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 126 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 127 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 128 |
+
" else:\n",
|
| 129 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"check_duplicates(df)"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"\n",
|
| 141 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"df.describe()"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"from sklearn.preprocessing import MinMaxScaler\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"scaler = MinMaxScaler()\n",
|
| 166 |
+
"df[features] = scaler.fit_transform(df[numerical_cols])\n",
|
| 167 |
+
"df.head()"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# 1. Is the target imbalanced?\n",
|
| 177 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 178 |
+
" print(\"Target Distribution:\")\n",
|
| 179 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 180 |
+
" sns.countplot(x=df[target_column])\n",
|
| 181 |
+
" plt.title(\"Target Distribution\")\n",
|
| 182 |
+
" plt.show()\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"check_target_imbalance(df, \"Target\")"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"X = df.drop(\"Target\", axis=1)\n",
|
| 194 |
+
"y = df['Target']"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 204 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 216 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Storage for logistic regression results for each fold\n",
|
| 226 |
+
"lr_losses = []\n",
|
| 227 |
+
"lr_accuracy = []\n",
|
| 228 |
+
"lr_precision = []\n",
|
| 229 |
+
"lr_recall = []\n",
|
| 230 |
+
"lr_f1 = []"
|
| 231 |
+
],
|
| 232 |
+
"execution_count": null,
|
| 233 |
+
"outputs": []
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "code",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": [
|
| 239 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 240 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 243 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 244 |
+
"\n",
|
| 245 |
+
""
|
| 246 |
+
],
|
| 247 |
+
"execution_count": null,
|
| 248 |
+
"outputs": []
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"# Import models\n",
|
| 255 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 256 |
+
"from sklearn.svm import SVC\n",
|
| 257 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 258 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 259 |
+
"from xgboost import XGBClassifier\n",
|
| 260 |
+
"from catboost import CatBoostClassifier"
|
| 261 |
+
],
|
| 262 |
+
"execution_count": null,
|
| 263 |
+
"outputs": []
|
| 264 |
+
},
|
| 265 |
+
{
|
| 266 |
+
"cell_type": "code",
|
| 267 |
+
"metadata": {},
|
| 268 |
+
"source": [
|
| 269 |
+
"sklearn_models = { \"CatBoost\": CatBoostClassifier(\n",
|
| 270 |
+
" verbose=0,\n",
|
| 271 |
+
" n_estimators=320,\n",
|
| 272 |
+
" max_depth=4\n",
|
| 273 |
+
" )\n",
|
| 274 |
+
"}"
|
| 275 |
+
],
|
| 276 |
+
"execution_count": null,
|
| 277 |
+
"outputs": []
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"cell_type": "code",
|
| 281 |
+
"metadata": {},
|
| 282 |
+
"source": [
|
| 283 |
+
"all_results = {}\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"for name in sklearn_models:\n",
|
| 286 |
+
" all_results[name] = {'accuracy': [], 'f1': []}"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 296 |
+
"importances = {}\n",
|
| 297 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"# Create a 1x3 plot\n",
|
| 300 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 301 |
+
"axes = axes.flatten()\n",
|
| 302 |
+
"features = X.columns\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 305 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 306 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" ax = axes[i]\n",
|
| 309 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 310 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 311 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"plt.tight_layout()\n",
|
| 314 |
+
"plt.show()"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Task 2: Write your code here:"
|
| 324 |
+
],
|
| 325 |
+
"execution_count": null,
|
| 326 |
+
"outputs": []
|
| 327 |
+
},
|
| 328 |
+
{
|
| 329 |
+
"cell_type": "code",
|
| 330 |
+
"metadata": {},
|
| 331 |
+
"source": [
|
| 332 |
+
"# Task Bonus: Write your code here:"
|
| 333 |
+
],
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"outputs": []
|
| 336 |
+
}
|
| 337 |
+
],
|
| 338 |
+
"metadata": {
|
| 339 |
+
"kernelspec": {
|
| 340 |
+
"display_name": "Python 3",
|
| 341 |
+
"name": "python3"
|
| 342 |
+
},
|
| 343 |
+
"language_info": {
|
| 344 |
+
"name": "python"
|
| 345 |
+
}
|
| 346 |
+
},
|
| 347 |
+
"nbformat": 4,
|
| 348 |
+
"nbformat_minor": 0
|
| 349 |
+
}
|
submissions_extracted/698/Q1.ipynb
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import numpy as np\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import matplotlib.pyplot as plt\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"import kagglehub\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder , OneHotEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"import warnings\n",
|
| 19 |
+
"warnings.filterwarnings('ignore')\n",
|
| 20 |
+
"\n"
|
| 21 |
+
],
|
| 22 |
+
"execution_count": null,
|
| 23 |
+
"outputs": []
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"metadata": {},
|
| 28 |
+
"source": [
|
| 29 |
+
"import kagglehub\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"# Download latest version\n",
|
| 32 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"print(\"Path to dataset files:\", path)"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# Task 1: Write your code here:\n",
|
| 44 |
+
"data_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 45 |
+
"data_df = pd.read_csv(data_path)"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 2: Write your code here:\n",
|
| 55 |
+
"data_df.head()"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 3: Write your code here:\n",
|
| 65 |
+
"data_df.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 |
+
"data_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 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 86 |
+
"plt.hist(data_df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 87 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 88 |
+
"plt.xlabel('elivery Time')\n",
|
| 89 |
+
"plt.ylabel('Frequency')\n",
|
| 90 |
+
"plt.show()"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 1: Write your code here:\n",
|
| 100 |
+
"df_clean = data_df.drop(columns=['Order_ID'])\n",
|
| 101 |
+
"df_clean.info()"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"df_clean.isna().sum()"
|
| 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 |
+
"\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 124 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"# for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 128 |
+
"# df_clean[col].fillna(df_clean[col].mode()[0])\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].median())\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].median())\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"df_clean.isnull().sum()"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 3: Write your code here:\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"def check_duplicates(df):\n",
|
| 157 |
+
" duplicates = df.duplicated().sum()\n",
|
| 158 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 159 |
+
" if duplicates > 0:\n",
|
| 160 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 161 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 162 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 163 |
+
" else:\n",
|
| 164 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"check_duplicates(df_clean)"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 4: Write your code here:\n",
|
| 187 |
+
"categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
|
| 188 |
+
"for col in categorical_cols:\n",
|
| 189 |
+
" le = LabelEncoder()\n",
|
| 190 |
+
" df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"df_clean.head()"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"# Task 5: Write your code here:\n",
|
| 202 |
+
"from sklearn.preprocessing import MinMaxScaler , StandardScaler\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"features = df_clean.columns.drop(\"Delivery_Time\")\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"scaler = StandardScaler()\n",
|
| 207 |
+
"df_clean[features] = scaler.fit_transform(df_clean[features])\n",
|
| 208 |
+
"df_clean.head()"
|
| 209 |
+
],
|
| 210 |
+
"execution_count": null,
|
| 211 |
+
"outputs": []
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"cell_type": "code",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"source": [
|
| 217 |
+
"# Task 6: Write your code here:\n",
|
| 218 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 219 |
+
"plt.hist(df_clean['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 220 |
+
"plt.ylabel('Frequency')\n",
|
| 221 |
+
"plt.show()"
|
| 222 |
+
],
|
| 223 |
+
"execution_count": null,
|
| 224 |
+
"outputs": []
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"cell_type": "code",
|
| 228 |
+
"metadata": {},
|
| 229 |
+
"source": [
|
| 230 |
+
"# Task 1: Write your code here:\n",
|
| 231 |
+
"features = df_clean.columns.drop(\"Delivery_Time\")\n",
|
| 232 |
+
"X = df_clean[features]\n",
|
| 233 |
+
"y = df_clean['Delivery_Time']\n",
|
| 234 |
+
"\n"
|
| 235 |
+
],
|
| 236 |
+
"execution_count": null,
|
| 237 |
+
"outputs": []
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"cell_type": "code",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"source": [
|
| 243 |
+
"from sklearn.metrics import mean_squared_error as mean_absolute_error, r2_score"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"models = {\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 255 |
+
" \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
|
| 256 |
+
" \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
|
| 257 |
+
"}\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"n_splits = 5"
|
| 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 |
+
"all_results = {}\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"for name in models:\n",
|
| 272 |
+
" all_results[name] = {'mae': [], 'rmse': [], 'r2': []}\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 279 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 282 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" for model_name, model in models.items():\n",
|
| 285 |
+
" print(f\"Training {model_name}...\")\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" # Train\n",
|
| 288 |
+
" model.fit(X_train, y_train)\n",
|
| 289 |
+
"\n",
|
| 290 |
+
" # Predict\n",
|
| 291 |
+
" y_pred = model.predict(X_test)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 296 |
+
" mae = mean_absolute_error(y_test ,y_pred )\n",
|
| 297 |
+
"\n",
|
| 298 |
+
" # Store results\n",
|
| 299 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 300 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"\n"
|
| 304 |
+
],
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"outputs": []
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"cell_type": "code",
|
| 310 |
+
"metadata": {},
|
| 311 |
+
"source": [
|
| 312 |
+
"from sklearn.linear_model import Ridge, Lasso"
|
| 313 |
+
],
|
| 314 |
+
"execution_count": null,
|
| 315 |
+
"outputs": []
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"source": [
|
| 321 |
+
"# Task 1: Write your code here:\n",
|
| 322 |
+
"coeffs = {}\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
|
| 325 |
+
"coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
|
| 328 |
+
"axes = axes.flatten()\n",
|
| 329 |
+
"features = X.columns\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"for i, (model_name, coef) in enumerate(coeffs.items()):\n",
|
| 332 |
+
" # Sort features by absolute coefficient value\n",
|
| 333 |
+
" absolute_coef = np.abs(coef)\n",
|
| 334 |
+
" sorted_idx = np.argsort(absolute_coef)\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" ax = axes[i]\n",
|
| 337 |
+
" ax.barh(features[sorted_idx], coef[sorted_idx])\n",
|
| 338 |
+
" ax.set_title(f\"{model_name} Coefficients\")\n",
|
| 339 |
+
" ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"plt.tight_layout()\n",
|
| 342 |
+
"plt.show()"
|
| 343 |
+
],
|
| 344 |
+
"execution_count": null,
|
| 345 |
+
"outputs": []
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"cell_type": "code",
|
| 349 |
+
"metadata": {},
|
| 350 |
+
"source": [
|
| 351 |
+
"\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"y_pred.s\n"
|
| 354 |
+
],
|
| 355 |
+
"execution_count": null,
|
| 356 |
+
"outputs": []
|
| 357 |
+
},
|
| 358 |
+
{
|
| 359 |
+
"cell_type": "code",
|
| 360 |
+
"metadata": {},
|
| 361 |
+
"source": [
|
| 362 |
+
"# Task Bonus: Write your code here:\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 366 |
+
"from sklearn.svm import SVR\n",
|
| 367 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 368 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 369 |
+
"from lightgbm import LGBMRegressor\n",
|
| 370 |
+
"\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"models = {\n",
|
| 375 |
+
" \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
|
| 376 |
+
" \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
|
| 377 |
+
" \"Support Vector Machine\": SVR(kernel='rbf'),\n",
|
| 378 |
+
" \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n",
|
| 379 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 380 |
+
" \"LightGBM\": LGBMRegressor(verbose=-1),\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"}\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"\n",
|
| 386 |
+
"all_results = {}\n",
|
| 387 |
+
"\n",
|
| 388 |
+
"for name in models:\n",
|
| 389 |
+
" all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"\n",
|
| 396 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 397 |
+
"\n",
|
| 398 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 399 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 400 |
+
"\n",
|
| 401 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 402 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 403 |
+
"\n",
|
| 404 |
+
" for model_name, model in models.items():\n",
|
| 405 |
+
" print(f\"Training {model_name}...\")\n",
|
| 406 |
+
"\n",
|
| 407 |
+
" # Train\n",
|
| 408 |
+
" model.fit(X_train, y_train)\n",
|
| 409 |
+
"\n",
|
| 410 |
+
" # Predict\n",
|
| 411 |
+
" y_pred = model.predict(X_test)\n",
|
| 412 |
+
"\n",
|
| 413 |
+
" # Calculate metrics\n",
|
| 414 |
+
"\n",
|
| 415 |
+
"\n",
|
| 416 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 417 |
+
"\n",
|
| 418 |
+
" # Store results\n",
|
| 419 |
+
"\n",
|
| 420 |
+
" all_results[model_name][\"rmse\"].append(rmse)\n",
|
| 421 |
+
" all_results[model_name][\"r2\"].append(r2)"
|
| 422 |
+
],
|
| 423 |
+
"execution_count": null,
|
| 424 |
+
"outputs": []
|
| 425 |
+
}
|
| 426 |
+
],
|
| 427 |
+
"metadata": {
|
| 428 |
+
"kernelspec": {
|
| 429 |
+
"display_name": "Python 3",
|
| 430 |
+
"name": "python3"
|
| 431 |
+
},
|
| 432 |
+
"language_info": {
|
| 433 |
+
"name": "python"
|
| 434 |
+
}
|
| 435 |
+
},
|
| 436 |
+
"nbformat": 4,
|
| 437 |
+
"nbformat_minor": 0
|
| 438 |
+
}
|
submissions_extracted/698/Q2.ipynb
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import torch\n",
|
| 8 |
+
"import torch.nn as nn\n",
|
| 9 |
+
"from torchvision.datasets import MNIST\n",
|
| 10 |
+
"from torch.utils.data import DataLoader\n",
|
| 11 |
+
"from torch.optim import Adam\n",
|
| 12 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 13 |
+
"import torch.nn.functional as F\n",
|
| 14 |
+
"import matplotlib.pyplot as plt\n",
|
| 15 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 16 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 17 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 18 |
+
"from torch.utils.data import TensorDataset\n",
|
| 19 |
+
"from torch.utils.data import DataLoader\n"
|
| 20 |
+
],
|
| 21 |
+
"execution_count": null,
|
| 22 |
+
"outputs": []
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": [
|
| 28 |
+
"import kagglehub\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"# Download latest version\n",
|
| 31 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"print(\"Path to dataset files:\", path)"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"import os\n",
|
| 43 |
+
"import pandas as pd\n",
|
| 44 |
+
"import numpy as np\n",
|
| 45 |
+
"from PIL import Image\n",
|
| 46 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"# Load Labels\n",
|
| 49 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 50 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"images = []\n",
|
| 53 |
+
"ages = []\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"# Load Images and Resize\n",
|
| 56 |
+
"print(\"Loading images...\")\n",
|
| 57 |
+
"for index, row in labels_df.iterrows():\n",
|
| 58 |
+
" img_name = row.iloc[0]\n",
|
| 59 |
+
" age = row.iloc[1]\n",
|
| 60 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 61 |
+
"\n",
|
| 62 |
+
" if os.path.exists(img_path):\n",
|
| 63 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 64 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 65 |
+
" images.append(img_array)\n",
|
| 66 |
+
" ages.append(age)\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"X = np.array(images)\n",
|
| 69 |
+
"y = np.array(ages)\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 72 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"# Split Data\n",
|
| 75 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 78 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 79 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 80 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 92 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 93 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 94 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\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 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 105 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 106 |
+
"\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 |
+
"from torch.utils.data import DataLoader\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"# DataLoader for training data\n",
|
| 120 |
+
"train_loader = DataLoader(\n",
|
| 121 |
+
" train_dataset,\n",
|
| 122 |
+
" batch_size=32,\n",
|
| 123 |
+
" shuffle=True,\n",
|
| 124 |
+
" num_workers=2\n",
|
| 125 |
+
")\n",
|
| 126 |
+
"# DataLoader for test/validation data\n",
|
| 127 |
+
"test_loader = DataLoader(\n",
|
| 128 |
+
" test_dataset,\n",
|
| 129 |
+
" batch_size=32,\n",
|
| 130 |
+
" shuffle=False,\n",
|
| 131 |
+
" num_workers=2\n",
|
| 132 |
+
")\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"\n"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# 4. Print shape of one batch\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 147 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 148 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# 5. Display sample images\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"images, labels = next(iter(train_loader))\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"# Display the first 6 images in the batch\n",
|
| 162 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"for i in range(6):\n",
|
| 165 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 166 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 167 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 168 |
+
" plt.axis('off')\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"plt.tight_layout()\n",
|
| 171 |
+
"plt.show()"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 1: Write your model class here:\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"class NN4Layer(nn.Module):\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 185 |
+
" super(NN4Layer, self).__init__()\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" self.relu = nn.ReLU()\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" def forward(self, x):\n",
|
| 206 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 207 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 208 |
+
" a3 = self.relu(self.layer2(a2))\n",
|
| 209 |
+
" output = self.layer3(a3)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" return output\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"\n"
|
| 219 |
+
],
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"outputs": []
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"source": [
|
| 227 |
+
"# Task 2: Write your training loop here:\n",
|
| 228 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 229 |
+
" # Set the model to training mode\n",
|
| 230 |
+
" model.train()\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" running_loss = 0.0\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 235 |
+
" # Move batch to the selected device\n",
|
| 236 |
+
" X_batch = X_batch.flatten(1).to(device) # shape: (batch_size, num_features)\n",
|
| 237 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" # Forward pass (outputs are logits)\n",
|
| 240 |
+
" outputs = model(X_batch)\n",
|
| 241 |
+
" loss = criterion(outputs, y_batch.unsqueeze(1)) # Convert the output from (batch , 1 ) to (Batch ,)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Backward pass & optimization\n",
|
| 244 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 245 |
+
" loss.backward() # Compute gradients\n",
|
| 246 |
+
" optimizer.step() # Update model parameters\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" running_loss += loss.item()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # Average loss over all batches\n",
|
| 251 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" return avg_loss"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"# Task 3: Write your validation loop here:\n",
|
| 263 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 264 |
+
" # Set the model to evaluation mode\n",
|
| 265 |
+
" model.eval()\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" running_loss = 0.0\n",
|
| 268 |
+
" correct = 0\n",
|
| 269 |
+
" total = 0\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" with torch.no_grad():\n",
|
| 272 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 273 |
+
" # Move data to device\n",
|
| 274 |
+
" X_batch = X_batch.flatten(1).to(device) # shape: (batch_size, num_features)\n",
|
| 275 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # Forward pass\n",
|
| 278 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 279 |
+
" loss = criterion(outputs, y_batch.unsqueeze(1))\n",
|
| 280 |
+
" running_loss += loss.item()\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" # Apply Softmax to get probabilities\n",
|
| 283 |
+
" # probabilities = F.softmax(outputs, dim=1)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" # # Pick the classes with highest probabilities\n",
|
| 286 |
+
" # predicted = torch.argmax(probabilities, dim=1)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" # # Accuracy calculation\n",
|
| 289 |
+
" # correct += (predicted == y_batch).sum().item()\n",
|
| 290 |
+
" # total += y_batch.size(0)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 293 |
+
" # accuracy = correct / total\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" return avg_loss"
|
| 296 |
+
],
|
| 297 |
+
"execution_count": null,
|
| 298 |
+
"outputs": []
|
| 299 |
+
},
|
| 300 |
+
{
|
| 301 |
+
"cell_type": "code",
|
| 302 |
+
"metadata": {},
|
| 303 |
+
"source": [
|
| 304 |
+
"X_batch.shape"
|
| 305 |
+
],
|
| 306 |
+
"execution_count": null,
|
| 307 |
+
"outputs": []
|
| 308 |
+
},
|
| 309 |
+
{
|
| 310 |
+
"cell_type": "code",
|
| 311 |
+
"metadata": {},
|
| 312 |
+
"source": [
|
| 313 |
+
"print(input_dim)"
|
| 314 |
+
],
|
| 315 |
+
"execution_count": null,
|
| 316 |
+
"outputs": []
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"cell_type": "code",
|
| 320 |
+
"metadata": {},
|
| 321 |
+
"source": [
|
| 322 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"# Device setup\n",
|
| 325 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"# Model paramete3rs\n",
|
| 328 |
+
"input_dim = 3 * 36 * 36\n",
|
| 329 |
+
"hidden_dim = 20\n",
|
| 330 |
+
"output_dim = 1\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"# Instantiate model\n",
|
| 333 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"# Print the model architecture\n",
|
| 336 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 337 |
+
"print(model)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"# Calculate the total number of trainable parameters\n",
|
| 340 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 341 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 342 |
+
],
|
| 343 |
+
"execution_count": null,
|
| 344 |
+
"outputs": []
|
| 345 |
+
},
|
| 346 |
+
{
|
| 347 |
+
"cell_type": "code",
|
| 348 |
+
"metadata": {},
|
| 349 |
+
"source": [
|
| 350 |
+
"from torch.optim import AdamW"
|
| 351 |
+
],
|
| 352 |
+
"execution_count": null,
|
| 353 |
+
"outputs": []
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"cell_type": "code",
|
| 357 |
+
"metadata": {},
|
| 358 |
+
"source": [
|
| 359 |
+
"num_epochs = 20\n",
|
| 360 |
+
"learning_rate = 0.001\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"criterion = nn.MSELoss()\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 366 |
+
],
|
| 367 |
+
"execution_count": null,
|
| 368 |
+
"outputs": []
|
| 369 |
+
},
|
| 370 |
+
{
|
| 371 |
+
"cell_type": "code",
|
| 372 |
+
"metadata": {},
|
| 373 |
+
"source": [
|
| 374 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 375 |
+
"\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"# Run Training\n",
|
| 379 |
+
"train_losses = []\n",
|
| 380 |
+
"val_losses = []\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"print('Starting Training...')\n",
|
| 383 |
+
"for epoch in range(num_epochs):\n",
|
| 384 |
+
" # TODO: Train one epoch using the train_one_epoch function\n",
|
| 385 |
+
" train_loss = train_one_epoch(model ,optimizer , criterion , train_loader , device)\n",
|
| 386 |
+
"\n",
|
| 387 |
+
" # TODO: Validate using the validate function\n",
|
| 388 |
+
" val_loss = validate(model , criterion , test_loader , device) # <Replace None with your code>\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" train_losses.append(train_loss)\n",
|
| 391 |
+
" val_losses.append(val_loss)\n",
|
| 392 |
+
"\n",
|
| 393 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"print('Training Complete!')"
|
| 396 |
+
],
|
| 397 |
+
"execution_count": null,
|
| 398 |
+
"outputs": []
|
| 399 |
+
},
|
| 400 |
+
{
|
| 401 |
+
"cell_type": "code",
|
| 402 |
+
"metadata": {},
|
| 403 |
+
"source": [
|
| 404 |
+
"# Task 1: Write your code here:\n",
|
| 405 |
+
"\n",
|
| 406 |
+
"# average_losses = np.mean(train_losses, axis=0)\n",
|
| 407 |
+
"\n",
|
| 408 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 409 |
+
"plt.plot(train_losses, label='Train loss')\n",
|
| 410 |
+
"plt.plot(val_losses, label='Validation loss')\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"plt.legend()\n",
|
| 413 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 414 |
+
"plt.show()"
|
| 415 |
+
],
|
| 416 |
+
"execution_count": null,
|
| 417 |
+
"outputs": []
|
| 418 |
+
},
|
| 419 |
+
{
|
| 420 |
+
"cell_type": "code",
|
| 421 |
+
"metadata": {},
|
| 422 |
+
"source": [
|
| 423 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 424 |
+
],
|
| 425 |
+
"execution_count": null,
|
| 426 |
+
"outputs": []
|
| 427 |
+
}
|
| 428 |
+
],
|
| 429 |
+
"metadata": {
|
| 430 |
+
"kernelspec": {
|
| 431 |
+
"display_name": "Python 3",
|
| 432 |
+
"name": "python3"
|
| 433 |
+
},
|
| 434 |
+
"language_info": {
|
| 435 |
+
"name": "python"
|
| 436 |
+
}
|
| 437 |
+
},
|
| 438 |
+
"nbformat": 4,
|
| 439 |
+
"nbformat_minor": 0
|
| 440 |
+
}
|
submissions_extracted/698/Q3.ipynb
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"import numpy as np\n",
|
| 27 |
+
"import pandas as pd\n",
|
| 28 |
+
"import matplotlib.pyplot as plt\n",
|
| 29 |
+
"import os\n",
|
| 30 |
+
"import kagglehub\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 33 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder , OneHotEncoder\n",
|
| 34 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 35 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"import warnings\n",
|
| 38 |
+
"warnings.filterwarnings('ignore')\n",
|
| 39 |
+
"\n"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Task 1: Write your code here:\n",
|
| 49 |
+
"data_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 50 |
+
"data_df = pd.read_csv(data_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 |
+
"data_df.head()"
|
| 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 |
+
"data_df.info()\n"
|
| 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 |
+
"\n",
|
| 82 |
+
"data_df.describe()"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"data_df.isna().sum()"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# Task 1: Write your code here:\n",
|
| 108 |
+
"df_clean = data_df.drop(columns=['D_142'])\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"for col in ['P_2', 'B_2', 'D_143' , 'D_144' , 'D_145' ]:\n",
|
| 113 |
+
" df_clean[col].fillna(df_clean[col].mode()[0])\n",
|
| 114 |
+
"\n"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 2: Write your code here:\n",
|
| 124 |
+
"\n",
|
| 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 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 145 |
+
"\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 3: Write your code here:\n",
|
| 156 |
+
"# Noneed"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 4: Write your code here:\n",
|
| 166 |
+
"from sklearn.preprocessing import MinMaxScaler , StandardScaler\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"features = df_clean.columns.drop(\"Target\")\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"scaler = StandardScaler()\n",
|
| 171 |
+
"df_clean[features] = scaler.fit_transform(df_clean[features])\n",
|
| 172 |
+
"df_clean.head()"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"# Task 5: Write your code here:\n",
|
| 182 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 183 |
+
"plt.hist(df_clean['Target'].dropna(), bins=50, edgecolor='black')\n",
|
| 184 |
+
"plt.ylabel('Frequency')\n",
|
| 185 |
+
"plt.show()"
|
| 186 |
+
],
|
| 187 |
+
"execution_count": null,
|
| 188 |
+
"outputs": []
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"metadata": {},
|
| 193 |
+
"source": [
|
| 194 |
+
"# Task 1: Write your code here:\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"features = df_clean.columns.drop(\"Target\")\n",
|
| 197 |
+
"X = df_clean[features]\n",
|
| 198 |
+
"y = df_clean['Target']"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"from IPython.display import clear_output\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"clear_output()"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"%matplotlib inline"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"\n",
|
| 230 |
+
"from catboost import CatBoostClassifier\n"
|
| 231 |
+
],
|
| 232 |
+
"execution_count": null,
|
| 233 |
+
"outputs": []
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "code",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": [
|
| 239 |
+
"sklearn_models = {\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 242 |
+
" verbose=0,\n",
|
| 243 |
+
" n_estimators=320,\n",
|
| 244 |
+
" max_depth=4\n",
|
| 245 |
+
" )\n",
|
| 246 |
+
"}"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"all_results = {}\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"for name in sklearn_models:\n",
|
| 258 |
+
" all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"from sklearn.model_selection import StratifiedKFold"
|
| 268 |
+
],
|
| 269 |
+
"execution_count": null,
|
| 270 |
+
"outputs": []
|
| 271 |
+
},
|
| 272 |
+
{
|
| 273 |
+
"cell_type": "code",
|
| 274 |
+
"metadata": {},
|
| 275 |
+
"source": [
|
| 276 |
+
"n_splits = 5 # K\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 279 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 280 |
+
],
|
| 281 |
+
"execution_count": null,
|
| 282 |
+
"outputs": []
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"metadata": {},
|
| 287 |
+
"source": [
|
| 288 |
+
"lr_f1 = []"
|
| 289 |
+
],
|
| 290 |
+
"execution_count": null,
|
| 291 |
+
"outputs": []
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"cell_type": "code",
|
| 295 |
+
"metadata": {},
|
| 296 |
+
"source": [
|
| 297 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
|
| 298 |
+
],
|
| 299 |
+
"execution_count": null,
|
| 300 |
+
"outputs": []
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"cell_type": "code",
|
| 304 |
+
"metadata": {},
|
| 305 |
+
"source": [
|
| 306 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"\n",
|
| 309 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 310 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" # 1. Split data\n",
|
| 313 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 314 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 315 |
+
"\n",
|
| 316 |
+
" # 2. Train & Validate sklearn models\n",
|
| 317 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 318 |
+
" print(f\"Training {model_name}...\")\n",
|
| 319 |
+
" model.fit(X_train, y_train) # train\n",
|
| 320 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"\n",
|
| 324 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" all_results[model_name]['f1'].append(f1)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"\n"
|
| 332 |
+
],
|
| 333 |
+
"execution_count": null,
|
| 334 |
+
"outputs": []
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"cell_type": "code",
|
| 338 |
+
"metadata": {},
|
| 339 |
+
"source": [
|
| 340 |
+
"print(f\" F1-Score: {np.mean(all_results['CatBoost']['f1']):.4f}\")"
|
| 341 |
+
],
|
| 342 |
+
"execution_count": null,
|
| 343 |
+
"outputs": []
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"cell_type": "code",
|
| 347 |
+
"metadata": {},
|
| 348 |
+
"source": [
|
| 349 |
+
"# Task 1: Write your code here:\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"importances = {}\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 360 |
+
"\n",
|
| 361 |
+
"features = X.columns\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 364 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 365 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 366 |
+
"\n",
|
| 367 |
+
" ax = axes[i]\n",
|
| 368 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 369 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 370 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"plt.tight_layout()\n",
|
| 373 |
+
"plt.show()"
|
| 374 |
+
],
|
| 375 |
+
"execution_count": null,
|
| 376 |
+
"outputs": []
|
| 377 |
+
},
|
| 378 |
+
{
|
| 379 |
+
"cell_type": "code",
|
| 380 |
+
"metadata": {},
|
| 381 |
+
"source": [
|
| 382 |
+
"# Task 2: Write your code here:"
|
| 383 |
+
],
|
| 384 |
+
"execution_count": null,
|
| 385 |
+
"outputs": []
|
| 386 |
+
},
|
| 387 |
+
{
|
| 388 |
+
"cell_type": "code",
|
| 389 |
+
"metadata": {},
|
| 390 |
+
"source": [
|
| 391 |
+
"# Task Bonus: Write your code here:\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"\n"
|
| 394 |
+
],
|
| 395 |
+
"execution_count": null,
|
| 396 |
+
"outputs": []
|
| 397 |
+
}
|
| 398 |
+
],
|
| 399 |
+
"metadata": {
|
| 400 |
+
"kernelspec": {
|
| 401 |
+
"display_name": "Python 3",
|
| 402 |
+
"name": "python3"
|
| 403 |
+
},
|
| 404 |
+
"language_info": {
|
| 405 |
+
"name": "python"
|
| 406 |
+
}
|
| 407 |
+
},
|
| 408 |
+
"nbformat": 4,
|
| 409 |
+
"nbformat_minor": 0
|
| 410 |
+
}
|
submissions_extracted/699/Q1.ipynb
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"# Download latest version\n",
|
| 11 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"print(\"Path to dataset files:\", path)"
|
| 14 |
+
],
|
| 15 |
+
"execution_count": null,
|
| 16 |
+
"outputs": []
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"cell_type": "code",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"# Task 1: Write your code here:\n",
|
| 23 |
+
"import pandas as pd\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n"
|
| 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 |
+
"\n",
|
| 36 |
+
"df.head()"
|
| 37 |
+
],
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"outputs": []
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Task 3: Write your code here:\n",
|
| 46 |
+
"df.info()"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 4: Write your code here:\n",
|
| 56 |
+
"df.describe()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 5: Write your code here:\n",
|
| 66 |
+
"df['Delivery_Time'].hist()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 1: Write your code here:\n",
|
| 76 |
+
"df.drop('Order_ID',axis=1,inplace=True)"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 2: Write your code here:\n",
|
| 86 |
+
"df.isnull().sum()\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"df['Weather']=df['Weather'].fillna(df['Weather'].mode()[0])\n",
|
| 89 |
+
"df['Traffic_Level']=df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
|
| 90 |
+
"df['Time_of_Day']=df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"df['Courier_Experience_yrs']=df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n",
|
| 93 |
+
"df['Delivery_Time']=df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"df.isnull().sum()"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# Task 3: Write your code here:\n",
|
| 105 |
+
"df.drop_duplicates(inplace=True)\n",
|
| 106 |
+
"df.duplicated()\n"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# Task 4: Write your code here:\n",
|
| 116 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 117 |
+
"le=LabelEncoder()\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"col=df.select_dtypes(include=['object']).columns\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"for c in df[col]:\n",
|
| 122 |
+
" df[c]=le.fit_transform(df[c])\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"df.info()"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 5: Write your code here:\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"X=df.drop('Delivery_Time',axis=1)\n",
|
| 136 |
+
"y=df['Delivery_Time']\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"#with out the target !!!\n",
|
| 145 |
+
"scaler = StandardScaler()\n",
|
| 146 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
| 147 |
+
"X_test_scaled = scaler.transform(X_test)\n"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 6: Write your code here:\n"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 1: Write your code here:\n",
|
| 166 |
+
"#i did above\n"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 176 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 177 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 178 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 179 |
+
"import numpy as np\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 184 |
+
"model.fit(X_train, y_train)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"mae_scores = []\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"for train_idx, val_idx in kfold.split(X_train_scaled):\n",
|
| 191 |
+
" X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
|
| 192 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Train and predict\n",
|
| 195 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 196 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # Calculate metrics\n",
|
| 199 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 204 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")\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:\n",
|
| 214 |
+
"# Feature importance\n",
|
| 215 |
+
"import matplotlib.pyplot as plt\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"feature_importance = pd.DataFrame({\n",
|
| 218 |
+
" 'feature': X.columns,\n",
|
| 219 |
+
" 'importance': model.feature_importances_\n",
|
| 220 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 223 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 224 |
+
"plt.xlabel('Importance')\n",
|
| 225 |
+
"plt.title('Feature Importance')\n",
|
| 226 |
+
"plt.gca().invert_yaxis()\n",
|
| 227 |
+
"plt.show()"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"# Task 2: Write your code here:\n",
|
| 237 |
+
"y_fold_train.hist()"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task Bonus: Write your code here:"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
}
|
| 251 |
+
],
|
| 252 |
+
"metadata": {
|
| 253 |
+
"kernelspec": {
|
| 254 |
+
"display_name": "Python 3",
|
| 255 |
+
"name": "python3"
|
| 256 |
+
},
|
| 257 |
+
"language_info": {
|
| 258 |
+
"name": "python"
|
| 259 |
+
}
|
| 260 |
+
},
|
| 261 |
+
"nbformat": 4,
|
| 262 |
+
"nbformat_minor": 0
|
| 263 |
+
}
|
submissions_extracted/699/Q2.ipynb
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"import torch\n",
|
| 71 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 72 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 75 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n",
|
| 76 |
+
"\n"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# 2. Create TensorDataset objects\n",
|
| 86 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
|
| 89 |
+
"test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\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 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 101 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 102 |
+
"\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# 4. Print shape of one batch\n",
|
| 112 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 115 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\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 |
+
"import matplotlib.pyplot as plt\n",
|
| 126 |
+
"images,labels = next(iter(train_loader))\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"# Display the first 6 images in the batch\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"for i in range(6):\n",
|
| 133 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 134 |
+
"\n",
|
| 135 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 136 |
+
" img = images[i].permute(1, 2, 0) # permute will re order it\n",
|
| 137 |
+
"\n",
|
| 138 |
+
" plt.imshow(img)\n",
|
| 139 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 140 |
+
" plt.axis('off')\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"plt.tight_layout()\n",
|
| 143 |
+
"plt.show()\n"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"from torchvision.datasets import CIFAR10\n",
|
| 153 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 154 |
+
"from torch.utils.data import DataLoader\n",
|
| 155 |
+
"import torch.nn as nn\n",
|
| 156 |
+
"import torch.nn.functional as F\n",
|
| 157 |
+
"import torch\n",
|
| 158 |
+
"from torch.optim import Adam"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 1: Write your model class here:\n",
|
| 168 |
+
"class NN4Layer(nn.Module):\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 171 |
+
" super(NN4Layer, self).__init__()\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" self.layer1 = nn.Linear(input_dim,hidden_dim)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" self.layer2 = nn.Linear(hidden_dim,hidden_dim)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" self.layer3 = nn.Linear(hidden_dim,hidden_dim)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" self.layer4 = nn.Linear(hidden_dim,output_dim)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # activation function for non-linearity\n",
|
| 182 |
+
" self.relu = nn.ReLU()\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" def forward(self, x):\n",
|
| 185 |
+
" # Layer 1: TODO\n",
|
| 186 |
+
" z1 = self.layer1(x)\n",
|
| 187 |
+
" a1 = self.relu(z1)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # Layer 2 TODO\n",
|
| 190 |
+
" z2 = self.layer2(a1)\n",
|
| 191 |
+
" a2 = self.relu(z2)\n",
|
| 192 |
+
" # Layer 3 TODO\n",
|
| 193 |
+
" z3 = self.layer3(a2)\n",
|
| 194 |
+
" a3 = self.relu(z3)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" # Output layer TODO\n",
|
| 197 |
+
" z4 = self.layer5(a3)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" return z4"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task 2: Write your training loop here:\n",
|
| 210 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 211 |
+
" # Set the model to training mode\n",
|
| 212 |
+
" model.train()\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" running_loss = 0.0\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 217 |
+
" # Move batch to the selected device\n",
|
| 218 |
+
" X_batch = X_batch.to(device)\n",
|
| 219 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Forward pass\n",
|
| 222 |
+
" outputs = model(X_batch)\n",
|
| 223 |
+
" loss = criterion(outputs, y_batch) # احسب اللوس هنا\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Backward pass & optimization\n",
|
| 226 |
+
" #باك بروباقيشن\n",
|
| 227 |
+
" optimizer.zero_grad() # Clear previous gradients واصفر القردينت السابق عشان استبدله بالجديد\n",
|
| 228 |
+
" loss.backward() # Compute gradients واحسب القردينت\n",
|
| 229 |
+
" optimizer.step() # Update model parameters ثم اعدل البراميترز\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" running_loss += loss.item() # احدث الخسارة\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Average loss over all batches\n",
|
| 234 |
+
" avg_loss = running_loss / len(train_loader) # متوسط الخساره\n",
|
| 235 |
+
"\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 validation loop here:\n",
|
| 246 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 247 |
+
" # Set the model to evaluation mode\n",
|
| 248 |
+
" model.eval()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" running_loss = 0.0\n",
|
| 251 |
+
" correct = 0\n",
|
| 252 |
+
" total = 0\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" with torch.no_grad(): # Disable gradient computation\n",
|
| 255 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 256 |
+
" # Move batch to the selected device\n",
|
| 257 |
+
" X_batch = X_batch.to(device)\n",
|
| 258 |
+
" y_batch = y_batch.view(-1, 1).to(device) # يتاكد ان الليبل من شيب واحد\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Forward pass\n",
|
| 261 |
+
" outputs = model(X_batch)\n",
|
| 262 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 263 |
+
" running_loss += loss.item()\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Binary predictions\n",
|
| 266 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # Accuracy calculation\n",
|
| 269 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 270 |
+
" total += y_batch.size(0)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 273 |
+
" accuracy = correct / total\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" return avg_loss, accuracy\n"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 285 |
+
"# Device setup\n",
|
| 286 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# Model parameters\n",
|
| 289 |
+
"input_dim = 28 * 28 # MNIST images flattened\n",
|
| 290 |
+
"hidden_dim = 14 # Design choice\n",
|
| 291 |
+
"output_dim = 10\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# Instantiate model\n",
|
| 294 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Print the model architecture\n",
|
| 297 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 298 |
+
"print(model)\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# Calculate the total number of trainable parameters\n",
|
| 301 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 302 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 303 |
+
],
|
| 304 |
+
"execution_count": null,
|
| 305 |
+
"outputs": []
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"metadata": {},
|
| 310 |
+
"source": [
|
| 311 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 312 |
+
"num_epochs = 20\n",
|
| 313 |
+
"learning_rate = 0.001\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 316 |
+
"criterion = nn.MSELoss()\n",
|
| 317 |
+
"# Define optimizer\n",
|
| 318 |
+
"optimizer = Adam(model.parameters(), learning_rate)"
|
| 319 |
+
],
|
| 320 |
+
"execution_count": null,
|
| 321 |
+
"outputs": []
|
| 322 |
+
},
|
| 323 |
+
{
|
| 324 |
+
"cell_type": "code",
|
| 325 |
+
"metadata": {},
|
| 326 |
+
"source": [
|
| 327 |
+
"# Device configuration\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"# Run Training\n",
|
| 330 |
+
"train_losses = []\n",
|
| 331 |
+
"val_losses = []\n",
|
| 332 |
+
"val_accuracies = []\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"print('Starting Training...')\n",
|
| 335 |
+
"for epoch in range(num_epochs):\n",
|
| 336 |
+
" # Train one epoch\n",
|
| 337 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" # Validate\n",
|
| 340 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" train_losses.append(train_loss)\n",
|
| 343 |
+
" val_losses.append(val_loss)\n",
|
| 344 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"print('Training Complete!')"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"# Task 1: Write your code here:"
|
| 358 |
+
],
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"outputs": []
|
| 361 |
+
},
|
| 362 |
+
{
|
| 363 |
+
"cell_type": "code",
|
| 364 |
+
"metadata": {},
|
| 365 |
+
"source": [
|
| 366 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 367 |
+
],
|
| 368 |
+
"execution_count": null,
|
| 369 |
+
"outputs": []
|
| 370 |
+
}
|
| 371 |
+
],
|
| 372 |
+
"metadata": {
|
| 373 |
+
"kernelspec": {
|
| 374 |
+
"display_name": "Python 3",
|
| 375 |
+
"name": "python3"
|
| 376 |
+
},
|
| 377 |
+
"language_info": {
|
| 378 |
+
"name": "python"
|
| 379 |
+
}
|
| 380 |
+
},
|
| 381 |
+
"nbformat": 4,
|
| 382 |
+
"nbformat_minor": 0
|
| 383 |
+
}
|
submissions_extracted/699/Q3.ipynb
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\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 |
+
"df=pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 2: Write your code here:\n",
|
| 37 |
+
"df.head()"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 3: Write your code here:\n",
|
| 47 |
+
"df.info()"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 4: Write your code here:\n",
|
| 57 |
+
"df.describe()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 67 |
+
"categorical_cols"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"numerical_cols = df.select_dtypes(include=[\"number\"]).columns\n",
|
| 77 |
+
"numerical_cols"
|
| 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.fillna(df.mean())\n",
|
| 88 |
+
"df"
|
| 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 |
+
"df.duplicated()\n",
|
| 99 |
+
"df=df.drop_duplicates()"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 3: Write your code here:\n",
|
| 109 |
+
"categorical_cols"
|
| 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 |
+
"\n",
|
| 120 |
+
"X=df.drop('Target',axis=1)\n",
|
| 121 |
+
"y=df['Target']\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"numerical_cols=numerical_cols.drop('Target')\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"scaler = StandardScaler()\n",
|
| 132 |
+
"data_scaled = scaler.fit_transform(df[numerical_cols])"
|
| 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 |
+
"df['Target'].hist()"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 1: Write your code here:\n",
|
| 152 |
+
"#i did above"
|
| 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:\n",
|
| 162 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"from catboost import CatBoostClassifier\n",
|
| 165 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 166 |
+
"from sklearn.model_selection import train_test_split, KFold,StratifiedKFold\n",
|
| 167 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 168 |
+
"import numpy as np\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 173 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"lr_accuracy = []\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"lr_f1 = []\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"model = CatBoostClassifier(\n",
|
| 181 |
+
" verbose=0,\n",
|
| 182 |
+
" n_estimators=320,\n",
|
| 183 |
+
" max_depth=4\n",
|
| 184 |
+
" )\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 188 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 191 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # Train\n",
|
| 194 |
+
" model.fit(X_train, y_train)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" # Validate\n",
|
| 197 |
+
" y_pred=model.predict(X_test)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Calculate evaluation metrics\n",
|
| 201 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" # Store results\n",
|
| 206 |
+
" lr_accuracy.append(accuracy)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" lr_f1.append(f1)\n"
|
| 209 |
+
],
|
| 210 |
+
"execution_count": null,
|
| 211 |
+
"outputs": []
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"cell_type": "code",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"source": [
|
| 217 |
+
"from numpy._core.defchararray import count\n",
|
| 218 |
+
"print('Accuracy',sum(lr_accuracy)/len(lr_accuracy),\n",
|
| 219 |
+
" '\\nF1 SCORE ',sum(lr_f1)/len(lr_f1))\n"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 1: Write your code here:\n",
|
| 229 |
+
"# Feature importance\n",
|
| 230 |
+
"import matplotlib.pyplot as plt\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"feature_importance = pd.DataFrame({\n",
|
| 233 |
+
" 'feature': X.columns,\n",
|
| 234 |
+
" 'importance': model.feature_importances_\n",
|
| 235 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 238 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 239 |
+
"plt.xlabel('Importance')\n",
|
| 240 |
+
"plt.title('Feature Importance')\n",
|
| 241 |
+
"plt.gca().invert_yaxis()\n",
|
| 242 |
+
"plt.show()"
|
| 243 |
+
],
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "code",
|
| 249 |
+
"metadata": {},
|
| 250 |
+
"source": [
|
| 251 |
+
"# Task 2: Write your code here:\n",
|
| 252 |
+
"t=model.feature_importances_.argmax()\n",
|
| 253 |
+
"t"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"# Task Bonus: Write your code here:"
|
| 263 |
+
],
|
| 264 |
+
"execution_count": null,
|
| 265 |
+
"outputs": []
|
| 266 |
+
}
|
| 267 |
+
],
|
| 268 |
+
"metadata": {
|
| 269 |
+
"kernelspec": {
|
| 270 |
+
"display_name": "Python 3",
|
| 271 |
+
"name": "python3"
|
| 272 |
+
},
|
| 273 |
+
"language_info": {
|
| 274 |
+
"name": "python"
|
| 275 |
+
}
|
| 276 |
+
},
|
| 277 |
+
"nbformat": 4,
|
| 278 |
+
"nbformat_minor": 0
|
| 279 |
+
}
|
submissions_extracted/7/Q1.ipynb
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
"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 |
+
"delivery_path = os.path.join(path, 'time.csv')\n",
|
| 23 |
+
"df_delivery = pd.read_csv(delivery_time)\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"print(f\"Dataset shape: {df_delivery.shape}\")\n",
|
| 26 |
+
"df_delivery.head()"
|
| 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 |
+
],
|
| 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_delivery.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_delivery.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 |
+
"# Price distribution (target variable)\n",
|
| 66 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 67 |
+
"plt.hist(df_delivery['price'].dropna(), bins=50, edgecolor='black')\n",
|
| 68 |
+
"plt.title('Price Distribution')\n",
|
| 69 |
+
"plt.xlabel('Price')\n",
|
| 70 |
+
"plt.ylabel('Frequency')\n",
|
| 71 |
+
"plt.show()"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Task 1: Write your code here:\n",
|
| 81 |
+
"# Drop columns where 'Order_ID' or key features are missing - can't predict without them\n",
|
| 82 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 83 |
+
"df_clean = df_clean.drop(columns=['Order_ID'])\n",
|
| 84 |
+
"print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n",
|
| 85 |
+
"\n"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 2: Write your code here:\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"# since my data doesnt opene so dont know what is my excat name of my colume, so complete with these name\n",
|
| 98 |
+
"# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n",
|
| 99 |
+
"cols = ['price', 'year', 'manufacturer', 'condition', 'cylinders', 'fuel', 'odometer', 'transmission', 'type']\n",
|
| 100 |
+
"df_clean = df_delivery[cols].copy()\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"\n",
|
| 103 |
+
" # Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 104 |
+
"for col in ['manufacturer', 'condition', 'fuel', 'transmission', 'type']:\n",
|
| 105 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"# Fill cylinders with mode - discrete feature, mode is most representative\n",
|
| 108 |
+
"df_clean['cylinders'] = df_clean['cylinders'].fillna(df_clean['cylinders'].mode()[0])\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"#############################################################\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# Missing values\n",
|
| 115 |
+
"print(\"Missing values:\")\n",
|
| 116 |
+
"print(df_delivery.isnull().sum())"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 3: Write your code here:"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 4: Write your code here:\n",
|
| 135 |
+
"# Encode categorical columns - converts text to integers\n",
|
| 136 |
+
"categorical_cols = ['delivery_distance', 'traffic_conditions', 'order_details','restaurant preparation']\n",
|
| 137 |
+
"for col in categorical_cols:\n",
|
| 138 |
+
" le = LabelEncoder()\n",
|
| 139 |
+
" df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"df_clean.head()"
|
| 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 |
+
"\n",
|
| 152 |
+
"# compute that delivery_distance: takes longer time in traffic\n",
|
| 153 |
+
"df_clean['delivery_faster'] = 60 - df_clean['delivery_distance']\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"# Quick preview of engineered features\n",
|
| 158 |
+
"df_clean[['delivery_faster', 'delivery_distance']].head()\n"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 6: Write your code here:\n",
|
| 168 |
+
"class_weight='balanced'\n",
|
| 169 |
+
"weight = n_samples / (n_classes * n_samples_in_class)\n"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 1: Write your code here:\n",
|
| 179 |
+
"# Define features and target\n",
|
| 180 |
+
"feature_cols = stat_cols + ['delivery_distance', 'traffic_conditions', 'order_details','restaurant preparation']\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"X = df_clean[feature_cols]\n",
|
| 183 |
+
"y = df_clean['delivery_time']\n",
|
| 184 |
+
"\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 194 |
+
"# i used Stratified split\n",
|
| 195 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 196 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
|
| 197 |
+
"print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"# Scale features\n",
|
| 200 |
+
"scaler = StandardScaler()\n",
|
| 201 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
| 202 |
+
"X_test_scaled = scaler.transform(X_test)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"# Train RandomForestClassifier\n",
|
| 206 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 207 |
+
" class_weight='balanced', random_state=42)\n",
|
| 208 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 209 |
+
"print(\"Model trained!\")"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"cell_type": "code",
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"source": [
|
| 218 |
+
"# Task 1: Write your code here:\n",
|
| 219 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 220 |
+
"plt.hist(df_delivery['attack'].dropna(), bins=30, edgecolor='black')\n",
|
| 221 |
+
"plt.title('Attack Distribution')\n",
|
| 222 |
+
"plt.xlabel('Attack')\n",
|
| 223 |
+
"plt.ylabel('Frequency')\n",
|
| 224 |
+
"plt.show()"
|
| 225 |
+
],
|
| 226 |
+
"execution_count": null,
|
| 227 |
+
"outputs": []
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "code",
|
| 231 |
+
"metadata": {},
|
| 232 |
+
"source": [
|
| 233 |
+
"# Task 2: Write your code here:"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task Bonus: Write your code here:"
|
| 243 |
+
],
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
}
|
| 247 |
+
],
|
| 248 |
+
"metadata": {
|
| 249 |
+
"kernelspec": {
|
| 250 |
+
"display_name": "Python 3",
|
| 251 |
+
"name": "python3"
|
| 252 |
+
},
|
| 253 |
+
"language_info": {
|
| 254 |
+
"name": "python"
|
| 255 |
+
}
|
| 256 |
+
},
|
| 257 |
+
"nbformat": 4,
|
| 258 |
+
"nbformat_minor": 0
|
| 259 |
+
}
|
submissions_extracted/70/Q1.ipynb
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"# Task 1: Write your code here:\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"# 1.Load dataset (USE THE PATH PRINTED BY kagglehub)\n",
|
| 25 |
+
"df = pd.read_csv(f\"{path}/Q1_data.csv\")\n"
|
| 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 |
+
"\n",
|
| 36 |
+
"# 2. Inspect first rows\n",
|
| 37 |
+
"print(df.head())"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 3: Write your code here:\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"# 3. Dataset info\n",
|
| 49 |
+
"df.info()"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 4: Write your code here:\n",
|
| 59 |
+
"\n",
|
| 60 |
+
"# 4. Statistical description\n",
|
| 61 |
+
"print(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 |
+
"\n",
|
| 72 |
+
"# 5.Plot the target distribution (delivery_time)\n",
|
| 73 |
+
"def check_target_distribution(df, target_column):\n",
|
| 74 |
+
" plt.figure(figsize=(10, 5))\n",
|
| 75 |
+
" df[target_column].hist(bins=30, edgecolor='red')\n",
|
| 76 |
+
" plt.title(\"Delivery Time Distribution\")\n",
|
| 77 |
+
" plt.xlabel(\"Delivery Time\")\n",
|
| 78 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 79 |
+
" plt.grid(False)\n",
|
| 80 |
+
" plt.show()\n",
|
| 81 |
+
"df = df.rename(columns={\"Delivery_Time\": \"delivery_time\"})\n",
|
| 82 |
+
"check_target_distribution(df, \"delivery_time\")\n"
|
| 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 |
+
"\n",
|
| 93 |
+
"if \"order_id\" in df.columns.str.lower():\n",
|
| 94 |
+
" df = df.drop(columns=[col for col in df.columns if col.lower() == \"order_id\"])\n"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 2: Write your code here:\n",
|
| 104 |
+
"# Check missing values\n",
|
| 105 |
+
"print(df.isnull().sum())\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"for col in df.columns:\n",
|
| 108 |
+
" if df[col].isnull().sum() > 0:\n",
|
| 109 |
+
" if df[col].dtype in [\"int64\", \"float64\"]:\n",
|
| 110 |
+
" df[col].fillna(df[col].median(), inplace=True)\n",
|
| 111 |
+
" else:\n",
|
| 112 |
+
" df[col].fillna(df[col].mode()[0], inplace=True)\n"
|
| 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 |
+
"# Check and remove duplicates\n",
|
| 123 |
+
"print(\"Duplicates before:\", df.duplicated().sum())\n",
|
| 124 |
+
"df = df.drop_duplicates()\n",
|
| 125 |
+
"print(\"Duplicates after:\", df.duplicated().sum())\n"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 4: Write your code here:\n",
|
| 135 |
+
"# Encode categorical variables\n",
|
| 136 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 139 |
+
"df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 5: Write your code here:\n",
|
| 149 |
+
"# Apply feature scaling for all features\n",
|
| 150 |
+
"from sklearn.preprocessing import StandardScaler #StandardScaler\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"scaler = StandardScaler()\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"X = df.drop(columns=[\"delivery_time\"]) # target out\n",
|
| 155 |
+
"y = df[\"delivery_time\"]\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"X_scaled = scaler.fit_transform(X)\n"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 6: Write your code here:\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"# Check for target imbalance and state if it is imbalanced or not\n",
|
| 169 |
+
"y.value_counts(normalize=True)\n"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 1: Write your code here:\n",
|
| 179 |
+
"# 1. Split the dataset into features (X) and target (y)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"from sklearn.model_selection import KFold\n",
|
| 182 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 183 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 184 |
+
"import numpy as np\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"X = df.drop(columns=[\"delivery_time\"])\n",
|
| 187 |
+
"y = df[\"delivery_time\"]\n",
|
| 188 |
+
"\n"
|
| 189 |
+
],
|
| 190 |
+
"execution_count": null,
|
| 191 |
+
"outputs": []
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42) # KFold\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"mae_scores = []\n",
|
| 202 |
+
" # tarin the model\n",
|
| 203 |
+
"for train_index, test_index in kf.split(X):\n",
|
| 204 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 205 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" model = RandomForestRegressor(\n",
|
| 208 |
+
" n_estimators=100,\n",
|
| 209 |
+
" random_state=42\n",
|
| 210 |
+
" )\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" model.fit(X_train, y_train)\n",
|
| 213 |
+
" y_pred = model.predict(X_test)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" #MAE\n",
|
| 217 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 218 |
+
" mae_scores.append(mae)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"#printing the Average MAE across folds\n",
|
| 221 |
+
"print(\"Average MAE across folds:\", np.mean(mae_scores))\n",
|
| 222 |
+
"\n"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"import numpy as np\n",
|
| 232 |
+
"import matplotlib.pyplot as plt\n",
|
| 233 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 234 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 235 |
+
"from sklearn.compose import ColumnTransformer\n",
|
| 236 |
+
"from sklearn.pipeline import Pipeline\n",
|
| 237 |
+
"from sklearn.impute import SimpleImputer\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"# Features and target\n",
|
| 240 |
+
"X = df.drop(\"delivery_time\", axis=1)\n",
|
| 241 |
+
"y = df[\"delivery_time\"]\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# Column types\n",
|
| 244 |
+
"categorical_cols = X.select_dtypes(include=\"object\").columns\n",
|
| 245 |
+
"numerical_cols = X.select_dtypes(exclude=\"object\").columns\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"# Preprocessing\n",
|
| 248 |
+
"preprocessor = ColumnTransformer([\n",
|
| 249 |
+
" (\"num\", SimpleImputer(strategy=\"median\"), numerical_cols),\n",
|
| 250 |
+
" (\"cat\", Pipeline([\n",
|
| 251 |
+
" (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n",
|
| 252 |
+
" (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\"))\n",
|
| 253 |
+
" ]), categorical_cols)\n",
|
| 254 |
+
"])\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"# Pipeline with RandomForest\n",
|
| 257 |
+
"pipeline = Pipeline([\n",
|
| 258 |
+
" (\"preprocessor\", preprocessor),\n",
|
| 259 |
+
" (\"model\", RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1))\n",
|
| 260 |
+
"])\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"# Fit the model\n",
|
| 263 |
+
"pipeline.fit(X, y)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"# Feature Importance Plot\n",
|
| 266 |
+
"# Get transformed feature names directly from preprocessor\n",
|
| 267 |
+
"all_features = pipeline.named_steps['preprocessor'].get_feature_names_out()\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"# Get feature importances from the RandomForest model\n",
|
| 270 |
+
"importances = pipeline.named_steps['model'].feature_importances_\n",
|
| 271 |
+
"indices = np.argsort(importances)[::-1] # sort descending\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"# Plot\n",
|
| 274 |
+
"plt.figure(figsize=(12, 6))\n",
|
| 275 |
+
"plt.bar(range(len(importances)), importances[indices])\n",
|
| 276 |
+
"plt.xticks(range(len(importances)), all_features[indices], rotation=90)\n",
|
| 277 |
+
"plt.title(\"Feature Importance\")\n",
|
| 278 |
+
"plt.show()\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"\n"
|
| 281 |
+
],
|
| 282 |
+
"execution_count": null,
|
| 283 |
+
"outputs": []
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"cell_type": "code",
|
| 287 |
+
"metadata": {},
|
| 288 |
+
"source": [
|
| 289 |
+
"# Task 2: Write your code here:\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Predicted Delivery Time Histogram\n",
|
| 292 |
+
"y_pred = pipeline.predict(X)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 295 |
+
"plt.hist(y_pred, bins=30, edgecolor='black')\n",
|
| 296 |
+
"plt.title(\"Predicted Delivery Time Distribution\")\n",
|
| 297 |
+
"plt.xlabel(\"Delivery Time (minutes)\")\n",
|
| 298 |
+
"plt.ylabel(\"Frequency\")\n",
|
| 299 |
+
"plt.show()\n"
|
| 300 |
+
],
|
| 301 |
+
"execution_count": null,
|
| 302 |
+
"outputs": []
|
| 303 |
+
},
|
| 304 |
+
{
|
| 305 |
+
"cell_type": "code",
|
| 306 |
+
"metadata": {},
|
| 307 |
+
"source": [
|
| 308 |
+
"# Task Bonus: Write your code here:\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"from IPython.display import clear_output\n",
|
| 312 |
+
"%pip install kagglehub catboost lightgbm tqdm -q\n",
|
| 313 |
+
"clear_output()\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"import numpy as np\n",
|
| 316 |
+
"from sklearn.model_selection import KFold\n",
|
| 317 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 318 |
+
"from catboost import CatBoostRegressor\n",
|
| 319 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 320 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 321 |
+
"from sklearn.compose import ColumnTransformer\n",
|
| 322 |
+
"from sklearn.pipeline import Pipeline\n",
|
| 323 |
+
"from sklearn.impute import SimpleImputer\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"# Features and target\n",
|
| 326 |
+
"X = df.drop(\"delivery_time\", axis=1)\n",
|
| 327 |
+
"y = df[\"delivery_time\"]\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"categorical_cols = X.select_dtypes(include=\"object\").columns\n",
|
| 330 |
+
"numerical_cols = X.select_dtypes(exclude=\"object\").columns\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"# Preprocessing pipeline\n",
|
| 333 |
+
"preprocessor = ColumnTransformer([\n",
|
| 334 |
+
" (\"num\", SimpleImputer(strategy=\"median\"), numerical_cols),\n",
|
| 335 |
+
" (\"cat\", Pipeline([\n",
|
| 336 |
+
" (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n",
|
| 337 |
+
" (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\"))\n",
|
| 338 |
+
" ]), categorical_cols)\n",
|
| 339 |
+
"])\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"# Define KFold\n",
|
| 342 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 343 |
+
"mae_scores = []\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"for train_idx, val_idx in kf.split(X):\n",
|
| 346 |
+
" X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
|
| 347 |
+
" y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
|
| 348 |
+
"\n",
|
| 349 |
+
" # RandomForest pipeline\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" rf_pipeline = Pipeline([\n",
|
| 352 |
+
" (\"preprocessor\", preprocessor),\n",
|
| 353 |
+
" (\"model\", RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1))\n",
|
| 354 |
+
" ])\n",
|
| 355 |
+
" rf_pipeline.fit(X_train, y_train)\n",
|
| 356 |
+
" rf_pred = rf_pipeline.predict(X_val)\n",
|
| 357 |
+
"\n",
|
| 358 |
+
" # CatBoost pipeline\n",
|
| 359 |
+
" cb_pipeline = Pipeline([\n",
|
| 360 |
+
" (\"preprocessor\", preprocessor),\n",
|
| 361 |
+
" (\"model\", CatBoostRegressor(\n",
|
| 362 |
+
" iterations=500,\n",
|
| 363 |
+
" learning_rate=0.1,\n",
|
| 364 |
+
" depth=6,\n",
|
| 365 |
+
" verbose=0,\n",
|
| 366 |
+
" random_state=42\n",
|
| 367 |
+
" ))\n",
|
| 368 |
+
" ])\n",
|
| 369 |
+
" cb_pipeline.fit(X_train, y_train)\n",
|
| 370 |
+
" cb_pred = cb_pipeline.predict(X_val)\n",
|
| 371 |
+
"\n",
|
| 372 |
+
" # Average predictions\n",
|
| 373 |
+
"\n",
|
| 374 |
+
" avg_pred = (rf_pred + cb_pred) / 2\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" # MAE for this fold\n",
|
| 377 |
+
" mae = mean_absolute_error(y_val, avg_pred)\n",
|
| 378 |
+
" mae_scores.append(mae)\n",
|
| 379 |
+
"\n",
|
| 380 |
+
"# Final result\n",
|
| 381 |
+
"print(f\"MAE per fold: {mae_scores}\")\n",
|
| 382 |
+
"print(f\"Average MAE across folds: {np.mean(mae_scores):.2f}\")\n"
|
| 383 |
+
],
|
| 384 |
+
"execution_count": null,
|
| 385 |
+
"outputs": []
|
| 386 |
+
}
|
| 387 |
+
],
|
| 388 |
+
"metadata": {
|
| 389 |
+
"kernelspec": {
|
| 390 |
+
"display_name": "Python 3",
|
| 391 |
+
"name": "python3"
|
| 392 |
+
},
|
| 393 |
+
"language_info": {
|
| 394 |
+
"name": "python"
|
| 395 |
+
}
|
| 396 |
+
},
|
| 397 |
+
"nbformat": 4,
|
| 398 |
+
"nbformat_minor": 0
|
| 399 |
+
}
|
submissions_extracted/70/Q2.ipynb
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"import torch\n",
|
| 69 |
+
"from torch.utils.data import TensorDataset, DataLoader\n",
|
| 70 |
+
"import matplotlib.pyplot as plt\n",
|
| 71 |
+
"import numpy as np\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"# 1. Convert numpy arrays to PyTorch tensors\n",
|
| 74 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 75 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 76 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1) # make it (N, 1)\n",
|
| 77 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1)\n"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 2. Create TensorDataset objects\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
|
| 89 |
+
"test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\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 |
+
"\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"# 3. Create DataLoaders\n",
|
| 103 |
+
"batch_size = 32\n",
|
| 104 |
+
"train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n",
|
| 105 |
+
"test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n",
|
| 106 |
+
"\n"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# 4. Print shape of one batch\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"for images, labels in train_loader:\n",
|
| 118 |
+
" print(f\"Batch images shape: {images.shape}\") # should be (32, C, H, W)\n",
|
| 119 |
+
" print(f\"Batch labels shape: {labels.shape}\") # should be (32, 1)\n",
|
| 120 |
+
" break\n"
|
| 121 |
+
],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# 5. Display sample images\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"images, labels = next(iter(train_loader))\n",
|
| 132 |
+
"images = images.numpy()\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"plt.figure(figsize=(12, 6))\n",
|
| 135 |
+
"for i in range(6):\n",
|
| 136 |
+
" img = np.transpose(images[i], (1, 2, 0)) # convert back to HWC for matplotlib\n",
|
| 137 |
+
" plt.subplot(2, 3, i+1)\n",
|
| 138 |
+
" plt.imshow(img)\n",
|
| 139 |
+
" plt.title(f\"Age: {labels[i].item():.0f}\")\n",
|
| 140 |
+
" plt.axis('off')\n",
|
| 141 |
+
"plt.show()\n"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"# Task 1: Write your model class here:\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"import torch\n",
|
| 153 |
+
"import torch.nn as nn\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"class AgePredictor(nn.Module):\n",
|
| 156 |
+
" def __init__(self, input_size):\n",
|
| 157 |
+
" super(AgePredictor, self).__init__()\n",
|
| 158 |
+
" self.model = nn.Sequential(\n",
|
| 159 |
+
" nn.Linear(input_size, 1024),\n",
|
| 160 |
+
" nn.ReLU(),\n",
|
| 161 |
+
" nn.Linear(1024, 512),\n",
|
| 162 |
+
" nn.ReLU(),\n",
|
| 163 |
+
" nn.Linear(512, 256),\n",
|
| 164 |
+
" nn.ReLU(),\n",
|
| 165 |
+
" nn.Linear(256, 1) # regression output\n",
|
| 166 |
+
" )\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" def forward(self, x):\n",
|
| 169 |
+
" return self.model(x)\n"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 2: Write your training loop here:\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 181 |
+
"print(\"Using device:\", device)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"# Flattened image size\n",
|
| 184 |
+
"C, H, W = X_train.shape[1:]\n",
|
| 185 |
+
"input_size = C * H * W\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"model = AgePredictor(input_size).to(device)\n",
|
| 188 |
+
"criterion = nn.MSELoss() # regression loss\n",
|
| 189 |
+
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n"
|
| 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 |
+
"\n",
|
| 200 |
+
"def train_one_epoch(model, loader, criterion, optimizer, device):\n",
|
| 201 |
+
" model.train()\n",
|
| 202 |
+
" running_loss = 0\n",
|
| 203 |
+
" for images, labels in loader:\n",
|
| 204 |
+
" images = images.to(device)\n",
|
| 205 |
+
" labels = labels.to(device)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" # Flatten images\n",
|
| 208 |
+
" images = images.view(images.size(0), -1)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" optimizer.zero_grad()\n",
|
| 211 |
+
" outputs = model(images)\n",
|
| 212 |
+
" loss = criterion(outputs, labels)\n",
|
| 213 |
+
" loss.backward()\n",
|
| 214 |
+
" optimizer.step()\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" running_loss += loss.item() * images.size(0)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" epoch_loss = running_loss / len(loader.dataset)\n",
|
| 219 |
+
" return epoch_loss\n"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"def validate(model, loader, criterion, device):\n",
|
| 231 |
+
" model.eval()\n",
|
| 232 |
+
" running_loss = 0\n",
|
| 233 |
+
" with torch.no_grad():\n",
|
| 234 |
+
" for images, labels in loader:\n",
|
| 235 |
+
" images = images.to(device)\n",
|
| 236 |
+
" labels = labels.to(device)\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" images = images.view(images.size(0), -1)\n",
|
| 239 |
+
" outputs = model(images)\n",
|
| 240 |
+
" loss = criterion(outputs, labels)\n",
|
| 241 |
+
" running_loss += loss.item() * images.size(0)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" epoch_loss = running_loss / len(loader.dataset)\n",
|
| 244 |
+
" return epoch_loss\n"
|
| 245 |
+
],
|
| 246 |
+
"execution_count": null,
|
| 247 |
+
"outputs": []
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "code",
|
| 251 |
+
"metadata": {},
|
| 252 |
+
"source": [
|
| 253 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"num_epochs = 20\n",
|
| 256 |
+
"train_losses = []\n",
|
| 257 |
+
"val_losses = []\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"for epoch in range(num_epochs):\n",
|
| 260 |
+
" train_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n",
|
| 261 |
+
" val_loss = validate(model, test_loader, criterion, device)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" train_losses.append(train_loss)\n",
|
| 264 |
+
" val_losses.append(val_loss)\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" print(f\"Epoch [{epoch+1}/{num_epochs}] - Train Loss: {train_loss:.4f} - Val Loss: {val_loss:.4f}\")\n"
|
| 267 |
+
],
|
| 268 |
+
"execution_count": null,
|
| 269 |
+
"outputs": []
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": [
|
| 275 |
+
"# Task 1: Write your code here:\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"import matplotlib.pyplot as plt\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"plt.figure(figsize=(8,5))\n",
|
| 280 |
+
"plt.plot(range(1, num_epochs+1), train_losses, label='Training Loss', marker='o')\n",
|
| 281 |
+
"plt.plot(range(1, num_epochs+1), val_losses, label='Validation Loss', marker='o')\n",
|
| 282 |
+
"plt.title('Training vs Validation Loss')\n",
|
| 283 |
+
"plt.xlabel('Epochs')\n",
|
| 284 |
+
"plt.ylabel('MSE Loss')\n",
|
| 285 |
+
"plt.legend()\n",
|
| 286 |
+
"plt.grid(True)\n",
|
| 287 |
+
"plt.show()\n"
|
| 288 |
+
],
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"outputs": []
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"source": [
|
| 296 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"# Get a batch from test_loader\n",
|
| 299 |
+
"model.eval()\n",
|
| 300 |
+
"images, labels = next(iter(test_loader))\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"# Move to device and flatten\n",
|
| 303 |
+
"images_device = images.to(device)\n",
|
| 304 |
+
"outputs = model(images_device.view(images_device.size(0), -1))\n",
|
| 305 |
+
"preds = outputs.cpu().detach().numpy()\n",
|
| 306 |
+
"labels = labels.numpy()\n",
|
| 307 |
+
"images = images.numpy()\n",
|
| 308 |
+
"\n",
|
| 309 |
+
"# Display first 6 images with predicted vs actual ages\n",
|
| 310 |
+
"plt.figure(figsize=(12,6))\n",
|
| 311 |
+
"for i in range(6):\n",
|
| 312 |
+
" img = np.transpose(images[i], (1,2,0)) # C,H,W -> H,W,C\n",
|
| 313 |
+
" plt.subplot(2,3,i+1)\n",
|
| 314 |
+
" plt.imshow(img)\n",
|
| 315 |
+
" plt.title(f\"Pred: {preds[i][0]:.1f}, Actual: {labels[i][0]:.0f}\")\n",
|
| 316 |
+
" plt.axis('off')\n",
|
| 317 |
+
"plt.show()\n"
|
| 318 |
+
],
|
| 319 |
+
"execution_count": null,
|
| 320 |
+
"outputs": []
|
| 321 |
+
}
|
| 322 |
+
],
|
| 323 |
+
"metadata": {
|
| 324 |
+
"kernelspec": {
|
| 325 |
+
"display_name": "Python 3",
|
| 326 |
+
"name": "python3"
|
| 327 |
+
},
|
| 328 |
+
"language_info": {
|
| 329 |
+
"name": "python"
|
| 330 |
+
}
|
| 331 |
+
},
|
| 332 |
+
"nbformat": 4,
|
| 333 |
+
"nbformat_minor": 0
|
| 334 |
+
}
|
subm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
"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 |
+
"# Load the CSV file using the path (adjust filename if needed)\n",
|
| 29 |
+
"# Usually the download returns a folder, so you need the full file path\n",
|
| 30 |
+
"csv_file = path + \"/Q3_data.csv\" # Make sure the CSV name matches exactly\n",
|
| 31 |
+
"df = pd.read_csv(csv_file)\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 |
+
"# Inspect the first few rows, few is ambguis so i will choose 5\n",
|
| 42 |
+
"print(\"First 5 rows of the dataset:\")\n",
|
| 43 |
+
"print(df.head())\n"
|
| 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 |
+
"# Check dataset info (column types, non-null counts)\n",
|
| 54 |
+
"print(\"\\nDataset information:\")\n",
|
| 55 |
+
"print(df.info())\n"
|
| 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 |
+
"# Show summary statistics for numerical columns\n",
|
| 66 |
+
"print(\"\\nStatistical description of numerical features:\")\n",
|
| 67 |
+
"print(df.describe())\n"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"import pandas as pd\n",
|
| 77 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# Handle missing values\n",
|
| 80 |
+
"num_cols = df.select_dtypes(include=['int64', 'float64']).columns\n",
|
| 81 |
+
"cat_cols = df.select_dtypes(include=['object']).columns\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"# Fill numerical columns with median\n",
|
| 84 |
+
"df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"# Fill categorical columns with mode if any exist\n",
|
| 87 |
+
"if len(cat_cols) > 0:\n",
|
| 88 |
+
" df[cat_cols] = df[cat_cols].fillna(df[cat_cols].mode().iloc[0])\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 |
+
"\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"# Remove duplicates\n",
|
| 101 |
+
"duplicates = df.duplicated().sum()\n",
|
| 102 |
+
"if duplicates > 0:\n",
|
| 103 |
+
" df = df.drop_duplicates()"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 3: Write your code here:\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# Encode categorical variables if needed\n",
|
| 115 |
+
"if len(cat_cols) > 0:\n",
|
| 116 |
+
" for col in cat_cols:\n",
|
| 117 |
+
" le = LabelEncoder()\n",
|
| 118 |
+
" df[col] = le.fit_transform(df[col])"
|
| 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 |
+
"# Feature scaling for numerical features\n",
|
| 129 |
+
"scaler = StandardScaler()\n",
|
| 130 |
+
"df[num_cols] = scaler.fit_transform(df[num_cols])"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 5: Write your code here:\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"# Check target imbalance\n",
|
| 142 |
+
"target_col = 'Target' # replace with actual target column name if different\n",
|
| 143 |
+
"target_counts = df[target_col].value_counts()\n",
|
| 144 |
+
"print(\"Target value counts:\")\n",
|
| 145 |
+
"print(target_counts)\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"if len(target_counts) >= 2:\n",
|
| 148 |
+
" imbalance_ratio = target_counts.iloc[0] / target_counts.iloc[1]\n",
|
| 149 |
+
" if imbalance_ratio > 2 or imbalance_ratio < 0.5:\n",
|
| 150 |
+
" print(\"The target is imbalanced.\")\n",
|
| 151 |
+
" else:\n",
|
| 152 |
+
" print(\"The target is fairly balanced.\")\n",
|
| 153 |
+
"else:\n",
|
| 154 |
+
" print(\"Only one unique target value found, cannot compute imbalance.\")"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 1: Write your code here:\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"# Task 1: Split dataset into features and target\n",
|
| 166 |
+
"X = df.drop('Target', axis=1) # Replace 'Target' with your actual target column name\n",
|
| 167 |
+
"y = df['Target']\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"print(\"Features shape:\", X.shape)\n",
|
| 170 |
+
"print(\"Target shape:\", y.shape)\n"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"import pandas as pd\n",
|
| 180 |
+
"from catboost import CatBoostRegressor\n",
|
| 181 |
+
"from sklearn.model_selection import KFold\n",
|
| 182 |
+
"from sklearn.metrics import mean_squared_error\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"# Initialize K-Fold\n",
|
| 186 |
+
"n_splits = 5\n",
|
| 187 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"# Train CatBoostRegressor and evaluate\n",
|
| 190 |
+
"mse_scores = []\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"for train_index, test_index in kf.split(X):\n",
|
| 193 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 194 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" model = CatBoostRegressor(\n",
|
| 197 |
+
" iterations=500,\n",
|
| 198 |
+
" learning_rate=0.1,\n",
|
| 199 |
+
" depth=6,\n",
|
| 200 |
+
" verbose=0,\n",
|
| 201 |
+
" random_seed=42\n",
|
| 202 |
+
" )\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" model.fit(X_train, y_train)\n",
|
| 205 |
+
" y_pred = model.predict(X_test)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" mse = mean_squared_error(y_test, y_pred)\n",
|
| 208 |
+
" mse_scores.append(mse)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"# Print averaged MSE across folds\n",
|
| 211 |
+
"avg_mse = sum(mse_scores) / len(mse_scores)\n",
|
| 212 |
+
"print(f\"Averaged MSE across {n_splits} folds: {avg_mse:.4f}\")\n"
|
| 213 |
+
],
|
| 214 |
+
"execution_count": null,
|
| 215 |
+
"outputs": []
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "code",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"source": [
|
| 221 |
+
"# Task 1: Write your code here:\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"import matplotlib.pyplot as plt\n",
|
| 224 |
+
"import pandas as pd\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"# Get feature importance from your trained CatBoost model\n",
|
| 227 |
+
"feature_importances = model.get_feature_importance()\n",
|
| 228 |
+
"feature_names = X.columns\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"# Create a DataFrame\n",
|
| 231 |
+
"fi_df = pd.DataFrame({\n",
|
| 232 |
+
" 'Feature': feature_names,\n",
|
| 233 |
+
" 'Importance': feature_importances\n",
|
| 234 |
+
"}).sort_values(by='Importance', ascending=False)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"# Plot\n",
|
| 237 |
+
"plt.figure(figsize=(12, 6))\n",
|
| 238 |
+
"plt.bar(fi_df['Feature'], fi_df['Importance'], color='skyblue')\n",
|
| 239 |
+
"plt.xticks(rotation=90)\n",
|
| 240 |
+
"plt.title(\"Feature Importance from CatBoost\")\n",
|
| 241 |
+
"plt.show()\n",
|
| 242 |
+
"\n"
|
| 243 |
+
],
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "code",
|
| 249 |
+
"metadata": {},
|
| 250 |
+
"source": [
|
| 251 |
+
"# Task 2: Write your code here:\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"# The most important feature\n",
|
| 254 |
+
"golden_feature = fi_df.iloc[0]['Feature']\n",
|
| 255 |
+
"print(\"Golden Feature:\", golden_feature)\n"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task Bonus: Retrain with Golden Feature Only\n",
|
| 265 |
+
"X_golden = X[[golden_feature]] # Keep only the golden feature\n",
|
| 266 |
+
"print(\"Shape of new X with golden feature only:\", X_golden.shape)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"from sklearn.model_selection import KFold\n",
|
| 269 |
+
"from sklearn.metrics import mean_squared_error\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 272 |
+
"golden_mse_scores = []\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"for train_index, test_index in kf.split(X_golden):\n",
|
| 275 |
+
" X_train, X_test = X_golden.iloc[train_index], X_golden.iloc[test_index]\n",
|
| 276 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" # Train CatBoostRegressor on single feature\n",
|
| 279 |
+
" model_golden = CatBoostRegressor(\n",
|
| 280 |
+
" iterations=500,\n",
|
| 281 |
+
" learning_rate=0.1,\n",
|
| 282 |
+
" depth=6,\n",
|
| 283 |
+
" verbose=0,\n",
|
| 284 |
+
" random_seed=42\n",
|
| 285 |
+
" )\n",
|
| 286 |
+
" model_golden.fit(X_train, y_train)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" # Evaluate\n",
|
| 289 |
+
" y_pred = model_golden.predict(X_test)\n",
|
| 290 |
+
" mse = mean_squared_error(y_test, y_pred)\n",
|
| 291 |
+
" golden_mse_scores.append(mse)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# Average MSE with golden feature\n",
|
| 294 |
+
"avg_golden_mse = sum(golden_mse_scores) / len(golden_mse_scores)\n",
|
| 295 |
+
"avg_golden_rmse = avg_golden_mse ** 0.5\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"print(f\"Average MSE with Golden Feature only: {avg_golden_mse:.4f}\")\n",
|
| 298 |
+
"print(f\"Average RMSE with Golden Feature only: {avg_golden_rmse:.4f}\")\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# Compare with full model metrics\n",
|
| 301 |
+
"print(f\"Average MSE with Full Model: {avg_mse:.4f}\")\n",
|
| 302 |
+
"print(f\"Average RMSE with Full Model: {avg_rmse:.4f}\")\n"
|
| 303 |
+
],
|
| 304 |
+
"execution_count": null,
|
| 305 |
+
"outputs": []
|
| 306 |
+
}
|
| 307 |
+
],
|
| 308 |
+
"metadata": {
|
| 309 |
+
"kernelspec": {
|
| 310 |
+
"display_name": "Python 3",
|
| 311 |
+
"name": "python3"
|
| 312 |
+
},
|
| 313 |
+
"language_info": {
|
| 314 |
+
"name": "python"
|
| 315 |
+
}
|
| 316 |
+
},
|
| 317 |
+
"nbformat": 4,
|
| 318 |
+
"nbformat_minor": 0
|
| 319 |
+
}
|
submissions_extracted/700/Q1.ipynb
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import os\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"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_path = os.path.join(path, \"Q1_data.csv\" )\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"df = pd.read_csv(csv_path)\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"df.head()"
|
| 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.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.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.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 |
+
"df['Delivery_Time'].hist()"
|
| 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 = df.drop('Order_ID')\n"
|
| 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 |
+
"missing_values = df.isnull().sum()\n",
|
| 89 |
+
"print(missing_values)"
|
| 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 |
+
"duplicates = df.duplicated().sum()\n",
|
| 100 |
+
"print(f\"Duplicates: {duplicates}\")"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 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 |
+
"# as it shown in the info we have Weather,Traffic_Level, Time_of_Day, Vehicle_Type\n",
|
| 122 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
|
| 127 |
+
"le = LabelEncoder()\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"# Encode the target column\n",
|
| 130 |
+
"df['Weather'] = le.fit_transform(df['Weather'])\n",
|
| 131 |
+
"df['Traffic_Level'] = le.fit_transform(df['Traffic_Level'])\n",
|
| 132 |
+
"df['Time_of_Day'] = le.fit_transform(df['Time_of_Day'])\n",
|
| 133 |
+
"df['Vehicle_Type'] = le.fit_transform(df['Vehicle_Type'])\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 5: Write your code here:\n",
|
| 145 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 146 |
+
"features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"scaler = StandardScaler()\n",
|
| 149 |
+
"df[features] = scaler.fit_transform(df[features])\n",
|
| 150 |
+
"df.head()"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 6: Write your code here:\n",
|
| 160 |
+
"df['Delivery_Time'].value_counts()"
|
| 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 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 171 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 181 |
+
"from sklearn.model_selection import KFold\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 186 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 189 |
+
"print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 192 |
+
"y_train, y_test = y.iloc[train_index], y.iloc[test_index]"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"model = RandomForestClassifier(\n",
|
| 204 |
+
" n_estimators=320, # Number of trees\n",
|
| 205 |
+
" max_depth=4)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"model.fit(X_train, y_train)\n",
|
| 208 |
+
"y_pred = model.predict(X_test)"
|
| 209 |
+
],
|
| 210 |
+
"execution_count": null,
|
| 211 |
+
"outputs": []
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"cell_type": "code",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"source": [
|
| 217 |
+
"# Task 1: Write your code here:\n",
|
| 218 |
+
"importance = pd.DataFrame({\n",
|
| 219 |
+
" 'feature': df.columns,\n",
|
| 220 |
+
" 'importance': model.feature_importances_\n",
|
| 221 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 224 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 225 |
+
"plt.xlabel('Importance')\n",
|
| 226 |
+
"plt.title('Feature Importance')\n",
|
| 227 |
+
"plt.gca().invert_yaxis()\n",
|
| 228 |
+
"plt.show()"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 2: Write your code here:"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task Bonus: Write your code here:"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
}
|
| 251 |
+
],
|
| 252 |
+
"metadata": {
|
| 253 |
+
"kernelspec": {
|
| 254 |
+
"display_name": "Python 3",
|
| 255 |
+
"name": "python3"
|
| 256 |
+
},
|
| 257 |
+
"language_info": {
|
| 258 |
+
"name": "python"
|
| 259 |
+
}
|
| 260 |
+
},
|
| 261 |
+
"nbformat": 4,
|
| 262 |
+
"nbformat_minor": 0
|
| 263 |
+
}
|
submissions_extracted/700/Q2.ipynb
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 71 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 74 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"\n"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# 2. Create TensorDataset objects\n",
|
| 86 |
+
"from torch.utils.data import TensorDataset\n",
|
| 87 |
+
"train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
|
| 88 |
+
"test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# 3. Create DataLoaders\n",
|
| 98 |
+
"from torch.utils.data import DataLoader\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n",
|
| 101 |
+
"test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"# 4. Print shape of one batch\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 113 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 114 |
+
"print(f\"Training batch labels shape: {y_batch.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 |
+
"import matplotlib.pyplot as plt\n",
|
| 125 |
+
"images, labels = next(iter(train_loader))\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"# Display the first 6 images in the batch\n",
|
| 128 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"for i in range(6):\n",
|
| 131 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 132 |
+
" plt.imshow(images[i].permute(1, 2, 0), cmap='gray')\n",
|
| 133 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 134 |
+
" plt.axis('off')\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"plt.tight_layout()\n",
|
| 137 |
+
"plt.show()\n",
|
| 138 |
+
"\n"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 1: Write your model class here:\n",
|
| 148 |
+
"import torch.nn as nn\n",
|
| 149 |
+
"class NN4Layer(nn.Module):\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 152 |
+
" super(NN4Layer, self).__init__()\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 155 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 158 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 161 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # ReLU activation for non-linearity\n",
|
| 166 |
+
" self.relu = nn.ReLU()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" def forward(self, x):\n",
|
| 169 |
+
" # First hidden layer\n",
|
| 170 |
+
" z1 = self.layer1(x)\n",
|
| 171 |
+
" a1 = self.relu(z1)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # Second hidden layer\n",
|
| 174 |
+
" z2 = self.layer2(a1)\n",
|
| 175 |
+
" a2 = self.relu(z2)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # third hidden layer\n",
|
| 178 |
+
" z3 = self.layer2(a2)\n",
|
| 179 |
+
" a3 = self.relu(z2)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # Output layer (raw scores / logits)\n",
|
| 182 |
+
" output = self.layer3(a3)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" return output"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 2: Write your training loop here:\n",
|
| 194 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 195 |
+
" # Set the model to training mode\n",
|
| 196 |
+
" model.train()\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" running_loss = 0.0\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 201 |
+
" # Move batch to the selected device\n",
|
| 202 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 203 |
+
" y_batch = y_batch.to(device)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" # Forward pass\n",
|
| 206 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 207 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" # Backward pass & optimization\n",
|
| 210 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 211 |
+
" loss.backward() # Compute gradients\n",
|
| 212 |
+
" optimizer.step() # Update model parameters\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" running_loss += loss.item()\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Average loss over all batches\n",
|
| 217 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" return avg_loss"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 3: Write your validation loop here:\n",
|
| 229 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 230 |
+
" # Set the model to evaluation mode\n",
|
| 231 |
+
" model.eval()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" running_loss = 0.0\n",
|
| 234 |
+
" correct = 0\n",
|
| 235 |
+
" total = 0\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" with torch.no_grad():\n",
|
| 238 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 239 |
+
" # Move data to device\n",
|
| 240 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 241 |
+
" y_batch = y_batch.to(device)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Forward pass\n",
|
| 244 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 245 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 246 |
+
" running_loss += loss.item()\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" # Apply Softmax to get probabilities\n",
|
| 249 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" # Multiclass predictions\n",
|
| 252 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" # Accuracy calculation\n",
|
| 255 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 256 |
+
" total += y_batch.size(0)\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 259 |
+
" accuracy = correct / total\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" return avg_loss, accuracy"
|
| 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 |
+
"\n",
|
| 273 |
+
"# Model parameters\n",
|
| 274 |
+
"input_dim = 36 * 36\n",
|
| 275 |
+
"hidden_dim = 14\n",
|
| 276 |
+
"output_dim = 1\n",
|
| 277 |
+
"# Instantiate model\n",
|
| 278 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"# Print the model architecture\n",
|
| 281 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 282 |
+
"print(model)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"# Calculate the total number of trainable parameters\n",
|
| 285 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 286 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 296 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 297 |
+
" # Set the model to training mode\n",
|
| 298 |
+
" model.train()\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" running_loss = 0.0\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 303 |
+
" # Move batch to the selected device\n",
|
| 304 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 305 |
+
" y_batch = y_batch.to(device)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" # Forward pass\n",
|
| 308 |
+
" outputs = model(X_batch)\n",
|
| 309 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" # Backward pass & optimization\n",
|
| 312 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 313 |
+
" loss.backward() # Compute gradients\n",
|
| 314 |
+
" optimizer.step() # Update model parameters\n",
|
| 315 |
+
"\n",
|
| 316 |
+
" running_loss += loss.item()\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" # Average loss over all batches\n",
|
| 319 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" return avg_loss"
|
| 322 |
+
],
|
| 323 |
+
"execution_count": null,
|
| 324 |
+
"outputs": []
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"cell_type": "code",
|
| 328 |
+
"metadata": {},
|
| 329 |
+
"source": [
|
| 330 |
+
"from torch.optim import Adam\n",
|
| 331 |
+
"num_epochs = 20\n",
|
| 332 |
+
"learning_rate = 0.001\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 335 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 336 |
+
"# Define optimizer\n",
|
| 337 |
+
"optimizer = Adam(model.parameters(), learning_rate)"
|
| 338 |
+
],
|
| 339 |
+
"execution_count": null,
|
| 340 |
+
"outputs": []
|
| 341 |
+
},
|
| 342 |
+
{
|
| 343 |
+
"cell_type": "code",
|
| 344 |
+
"metadata": {},
|
| 345 |
+
"source": [
|
| 346 |
+
"# Run Training\n",
|
| 347 |
+
"train_losses = []\n",
|
| 348 |
+
"val_losses = []\n",
|
| 349 |
+
"val_accuracies = []\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"print('Starting Training...')\n",
|
| 352 |
+
"for epoch in range(num_epochs):\n",
|
| 353 |
+
" # Train one epoch\n",
|
| 354 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 355 |
+
"\n",
|
| 356 |
+
" # Validate\n",
|
| 357 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" train_losses.append(train_loss)\n",
|
| 360 |
+
" val_losses.append(val_loss)\n",
|
| 361 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 362 |
+
"\n",
|
| 363 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"print('Training Complete!')"
|
| 366 |
+
],
|
| 367 |
+
"execution_count": null,
|
| 368 |
+
"outputs": []
|
| 369 |
+
},
|
| 370 |
+
{
|
| 371 |
+
"cell_type": "code",
|
| 372 |
+
"metadata": {},
|
| 373 |
+
"source": [
|
| 374 |
+
"# Task 1: Write your code here:\n",
|
| 375 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 378 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 379 |
+
"plt.title('Loss over Epochs')\n",
|
| 380 |
+
"plt.xlabel('Epoch')\n",
|
| 381 |
+
"plt.ylabel('Loss')\n",
|
| 382 |
+
"plt.legend()\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"plt.tight_layout()\n",
|
| 385 |
+
"plt.show()"
|
| 386 |
+
],
|
| 387 |
+
"execution_count": null,
|
| 388 |
+
"outputs": []
|
| 389 |
+
},
|
| 390 |
+
{
|
| 391 |
+
"cell_type": "code",
|
| 392 |
+
"metadata": {},
|
| 393 |
+
"source": [
|
| 394 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 395 |
+
],
|
| 396 |
+
"execution_count": null,
|
| 397 |
+
"outputs": []
|
| 398 |
+
}
|
| 399 |
+
],
|
| 400 |
+
"metadata": {
|
| 401 |
+
"kernelspec": {
|
| 402 |
+
"display_name":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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import os\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"# Download latest version\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\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 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\" )\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"df = pd.read_csv(csv_path)\n"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"# Task 2: Write your code here:\n",
|
| 40 |
+
"df.head()"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 3: Write your code here:\n",
|
| 50 |
+
"df.info()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 4: Write your code here:\n",
|
| 60 |
+
"df.describe()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 1: Write your code here:\n",
|
| 70 |
+
"missing_values = df.isnull().sum()\n",
|
| 71 |
+
"print(missing_values)"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"df_mean = df.copy()\n",
|
| 81 |
+
"df_mean['P_2'] = df_mean['P_2'].fillna(df_mean['P_2'].mean())\n",
|
| 82 |
+
"df_mean['B_2'] = df_mean['B_2'].fillna(df_mean['B_2'].mean())\n",
|
| 83 |
+
"df_mean['D_142'] = df_mean['B_2'].fillna(df_mean['B_2'].mean())\n",
|
| 84 |
+
"df_mean['D_143'] = df_mean['B_2'].fillna(df_mean['B_2'].mean())\n",
|
| 85 |
+
"df_mean['D_144'] = df_mean['B_2'].fillna(df_mean['B_2'].mean())\n",
|
| 86 |
+
"df_mean['D_144'] = df_mean['B_2'].fillna(df_mean['B_2'].mean())\n",
|
| 87 |
+
"print(\"\\n3. Fill with mean\")\n",
|
| 88 |
+
"print(df_mean)"
|
| 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 |
+
"duplicates = df.duplicated().sum()\n",
|
| 99 |
+
"print(f\"Duplicates: {duplicates}\")"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 3: Write your code here:\n",
|
| 109 |
+
"# As the output of info there is no categorical variables"
|
| 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 |
+
"features = df.columns\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"scaler = StandardScaler()\n",
|
| 123 |
+
"df[features] = scaler.fit_transform(df[features])\n",
|
| 124 |
+
"df.head()"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 5: Write your code here:\n",
|
| 134 |
+
"df['Target'].hist()\n",
|
| 135 |
+
"# it is imbalanced"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 1: Write your code here:\n",
|
| 145 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 146 |
+
"y = df['Target'].astype(float)"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 156 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"n_splits = 5 # K\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 161 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 164 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 165 |
+
"\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 |
+
"\n"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"from catboost import CatBoostClassifier\n",
|
| 178 |
+
"model = CatBoostClassifier(\n",
|
| 179 |
+
" verbose=0,\n",
|
| 180 |
+
" n_estimators=320,\n",
|
| 181 |
+
" max_depth=4)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"model.fit(X_train, y_train)\n",
|
| 184 |
+
"y_pred = model.predict(X_test)"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"from sklearn.metrics import accuracy_score,f1_score\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"accuracy = accuracy_score(y_test, y_pred)\n",
|
| 196 |
+
"f1 = f1_score(y_test, y_pred, zero_division=0)"
|
| 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 code here:\n",
|
| 213 |
+
"importance = pd.DataFrame({\n",
|
| 214 |
+
" 'feature': df.columns,\n",
|
| 215 |
+
" 'importance': model.feature_importances_\n",
|
| 216 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 219 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 220 |
+
"plt.xlabel('Importance')\n",
|
| 221 |
+
"plt.title('Feature Importance')\n",
|
| 222 |
+
"plt.gca().invert_yaxis()\n",
|
| 223 |
+
"plt.show()"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task 2: Write your code here:"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task Bonus: Write your code here:"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
}
|
| 246 |
+
],
|
| 247 |
+
"metadata": {
|
| 248 |
+
"kernelspec": {
|
| 249 |
+
"display_name": "Python 3",
|
| 250 |
+
"name": "python3"
|
| 251 |
+
},
|
| 252 |
+
"language_info": {
|
| 253 |
+
"name": "python"
|
| 254 |
+
}
|
| 255 |
+
},
|
| 256 |
+
"nbformat": 4,
|
| 257 |
+
"nbformat_minor": 0
|
| 258 |
+
}
|
submissions_extracted/701/Q1.ipynb
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"import pandas as pd\n",
|
| 23 |
+
"# Task 1: Write your code here:\n",
|
| 24 |
+
"data = os.path.join(path, 'Q1_data.csv')\n",
|
| 25 |
+
"data = pd.read_csv(data)\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(f\"Dataset shape: {data.shape}\")"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 2: Write your code here:\n",
|
| 37 |
+
"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 |
+
"data.info()"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 4: Write your code here:\n",
|
| 57 |
+
"data.describe()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"# Task 5: Write your code here:\n",
|
| 67 |
+
"import matplotlib.pyplot as plt\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 70 |
+
"plt.hist(data['Delivery_Time'].dropna(), bins=30, 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 |
+
"data = data.drop(\"Order_ID\", axis=1)\n",
|
| 85 |
+
"data.head()"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"data.isnull().sum()"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 2: Write your code here:\n",
|
| 104 |
+
"numerical_cols = data.select_dtypes(include=[\"int64\", \"float64\"])\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"for col in numerical_cols:\n",
|
| 107 |
+
" data[col] = data[col].fillna(data[col].mode()[0])\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"data"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# Task 3: Write your code here:\n",
|
| 119 |
+
"def check_duplicates(df):\n",
|
| 120 |
+
" duplicates = data.duplicated().sum()\n",
|
| 121 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 122 |
+
" if duplicates > 0:\n",
|
| 123 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 124 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 125 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 126 |
+
" else:\n",
|
| 127 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"check_duplicates(data)"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 139 |
+
"categorical_cols = data.select_dtypes(include=[\"object\"]).columns\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"label_encoders = {}\n",
|
| 145 |
+
"for col in categorical_cols:\n",
|
| 146 |
+
" le = LabelEncoder()\n",
|
| 147 |
+
" data[col] = le.fit_transform(data[col])\n",
|
| 148 |
+
" label_encoders[col] = le\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"data"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"numerical_cols = data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n",
|
| 160 |
+
"scaler = StandardScaler()\n",
|
| 161 |
+
"data[numerical_cols] = scaler.fit_transform(data[numerical_cols])\n",
|
| 162 |
+
"data.head()"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"import matplotlib.pyplot as plt\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 174 |
+
"plt.hist(data['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 175 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 176 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 177 |
+
"plt.ylabel('Frequency')\n",
|
| 178 |
+
"plt.show()"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# Task 6: Write your code here:"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 1: Write your code here:\n",
|
| 197 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"X = data.drop(\"Delivery_Time\" , axis=1)\n",
|
| 200 |
+
"y = data[\"Delivery_Time\"]\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"n_splits = 5 # K=3 Folds\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 1: Write your code here:"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"# Task 2: Write your code here:"
|
| 232 |
+
],
|
| 233 |
+
"execution_count": null,
|
| 234 |
+
"outputs": []
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"metadata": {},
|
| 239 |
+
"source": [
|
| 240 |
+
"# Task Bonus: Write your code here:"
|
| 241 |
+
],
|
| 242 |
+
"execution_count": null,
|
| 243 |
+
"outputs": []
|
| 244 |
+
}
|
| 245 |
+
],
|
| 246 |
+
"metadata": {
|
| 247 |
+
"kernelspec": {
|
| 248 |
+
"display_name": "Python 3",
|
| 249 |
+
"name": "python3"
|
| 250 |
+
},
|
| 251 |
+
"language_info": {
|
| 252 |
+
"name": "python"
|
| 253 |
+
}
|
| 254 |
+
},
|
| 255 |
+
"nbformat": 4,
|
| 256 |
+
"nbformat_minor": 0
|
| 257 |
+
}
|
submissions_extracted/701/Q2.ipynb
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"import torch\n",
|
| 69 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 70 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 71 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 72 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 73 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# 2. Create TensorDataset objects\n",
|
| 83 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 84 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 85 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# 3. Create DataLoaders\n",
|
| 95 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 96 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 97 |
+
"\n"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# 4. Print shape of one batch\n",
|
| 107 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 108 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 109 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"import matplotlib.pyplot as plt\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# 5. Display sample images\n",
|
| 121 |
+
"images, labels = next(iter(train_loader))\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# Display the first 6 images in the batch\n",
|
| 124 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"for i in range(6):\n",
|
| 127 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 130 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 131 |
+
"\n",
|
| 132 |
+
" plt.imshow(img)\n",
|
| 133 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 134 |
+
" plt.axis('off')\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"plt.tight_layout()\n",
|
| 137 |
+
"plt.show()\n"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# Task 1: Write your model class here:\n",
|
| 147 |
+
"import torch.nn as nn\n",
|
| 148 |
+
"class NN4Layer(nn.Module):\n",
|
| 149 |
+
" def __init__(self, input_dim, hidden_dim , output_dim):\n",
|
| 150 |
+
" super(NN4Layer, self).__init__()\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 153 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 154 |
+
"\n",
|
| 155 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 156 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" # Output layer: hidden layer -> single continuous value\n",
|
| 159 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 162 |
+
" # ReLU activation for non-linearity in hidden layers\n",
|
| 163 |
+
" self.relu = nn.ReLU()\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # Defines how input data flows through the network\n",
|
| 166 |
+
" def forward(self, x):\n",
|
| 167 |
+
" # First hidden layer\n",
|
| 168 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # Second hidden layer\n",
|
| 171 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" a3 = self.relu(self.layer2(a2))\n",
|
| 174 |
+
" # Output layer (regression output)\n",
|
| 175 |
+
" output = self.layer3(a3)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" return output"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 2: Write your training loop here:\n",
|
| 187 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 188 |
+
" # Set the model to training mode\n",
|
| 189 |
+
" model.train()\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" running_loss = 0.0\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 194 |
+
" # Move batch to the selected device\n",
|
| 195 |
+
" X_batch = X_batch.view(X_batch.size(0),-1).to(device) # shape: (batch_size, num_features)\n",
|
| 196 |
+
" y_batch = y_batch.unsqueeze(1).to(device)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # Forward pass (outputs are logits)\n",
|
| 199 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 200 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # Backward pass & optimization\n",
|
| 203 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 204 |
+
" loss.backward() # Compute gradients\n",
|
| 205 |
+
" optimizer.step() # Update model parameters\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" running_loss += loss.item()\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" # Average loss over all batches\n",
|
| 210 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" return avg_loss"
|
| 213 |
+
],
|
| 214 |
+
"execution_count": null,
|
| 215 |
+
"outputs": []
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "code",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"source": [
|
| 221 |
+
"# Task 3: Write your validation loop here:\n",
|
| 222 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 223 |
+
" # Set the model to evaluation mode\n",
|
| 224 |
+
" model.eval()\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" running_loss = 0.0\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" with torch.no_grad():\n",
|
| 229 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 230 |
+
" # Move data to device\n",
|
| 231 |
+
" X_batch = X_batch.view(X_batch.size(0),-1).to(device) # shape: (batch_size, num_features)\n",
|
| 232 |
+
" y_batch = y_batch.unsqueeze(1).to(device)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" # Forward pass (continuous output)\n",
|
| 235 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 236 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" running_loss += loss.item()\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Average loss over all batches\n",
|
| 241 |
+
" avg_loss = running_loss / len(test_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 4: Define device, model, loss, optimizer:\n",
|
| 253 |
+
"# Device setup\n",
|
| 254 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"# Model parameters\n",
|
| 257 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 258 |
+
"input_dim = 3 * 36 * 36 # CIFAR-10 images flattened (RGB)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"# TODO: choose number of hidden neurons\n",
|
| 261 |
+
"hidden_dim = 32 # Design choice\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"# TODO: what are the number of classes ?\n",
|
| 264 |
+
"output_dim = 1 # CIFAR-10 classes\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 267 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"# TODO: Print the model architecture\n",
|
| 270 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 271 |
+
"print(model)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"# Calculate the total number of trainable parameters\n",
|
| 274 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 275 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"from torch.optim import AdamW\n",
|
| 285 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 286 |
+
"# TODO: choose number of epochs, increase it if you have gpus :)\n",
|
| 287 |
+
"num_epochs = 20\n",
|
| 288 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 289 |
+
"learning_rate = 0.001\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 292 |
+
"criterion = nn.MSELoss()\n",
|
| 293 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 294 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"train_losses = []\n",
|
| 297 |
+
"val_losses = []\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"print('Starting Training...')\n",
|
| 300 |
+
"for epoch in range(num_epochs):\n",
|
| 301 |
+
" # Train one epoch\n",
|
| 302 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
" # Validate\n",
|
| 305 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" train_losses.append(train_loss)\n",
|
| 308 |
+
" val_losses.append(val_loss)\n",
|
| 309 |
+
"\n",
|
| 310 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 311 |
+
" print(\n",
|
| 312 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 313 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 314 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 315 |
+
" )\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"print('Training Complete!')"
|
| 318 |
+
],
|
| 319 |
+
"execution_count": null,
|
| 320 |
+
"outputs": []
|
| 321 |
+
},
|
| 322 |
+
{
|
| 323 |
+
"cell_type": "code",
|
| 324 |
+
"metadata": {},
|
| 325 |
+
"source": [
|
| 326 |
+
"# Task 1: Write your code here:\n",
|
| 327 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 330 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 331 |
+
"plt.title('Loss over Epochs')\n",
|
| 332 |
+
"plt.xlabel('Epoch')\n",
|
| 333 |
+
"plt.ylabel('Loss')\n",
|
| 334 |
+
"plt.legend()\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"plt.tight_layout()\n",
|
| 337 |
+
"plt.show()"
|
| 338 |
+
],
|
| 339 |
+
"execution_count": null,
|
| 340 |
+
"outputs": []
|
| 341 |
+
},
|
| 342 |
+
{
|
| 343 |
+
"cell_type": "code",
|
| 344 |
+
"metadata": {},
|
| 345 |
+
"source": [
|
| 346 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 347 |
+
"model.eval()\n",
|
| 348 |
+
"# Get one batch from the test DataLoader\n",
|
| 349 |
+
"images, labels = next(iter(test_loader))\n",
|
| 350 |
+
"# Move images to device\n",
|
| 351 |
+
"images = images.to(device)\n",
|
| 352 |
+
"labels = labels.to(device)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"with torch.no_grad():\n",
|
| 355 |
+
" # Flatten images before passing to the model\n",
|
| 356 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 357 |
+
" predictions = outputs.squeeze(1)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"# Move tensors back to CPU for plotting\n",
|
| 360 |
+
"images = images.cpu()\n",
|
| 361 |
+
"labels = labels.cpu()\n",
|
| 362 |
+
"predictions = predictions.cpu()\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"# Plot first 6 predictions\n",
|
| 365 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 366 |
+
"for i in range(6):\n",
|
| 367 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 368 |
+
" img = images[i].permute(1, 2, 0).numpy()\n",
|
| 369 |
+
" plt.imshow(img)\n",
|
| 370 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 371 |
+
" plt.axis('off')\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"plt.tight_layout()\n",
|
| 374 |
+
"plt.show()"
|
| 375 |
+
],
|
| 376 |
+
"execution_count": null,
|
| 377 |
+
"outputs": []
|
| 378 |
+
},
|
| 379 |
+
{
|
| 380 |
+
"cell_type": "code",
|
| 381 |
+
"metadata": {},
|
| 382 |
+
"source": [],
|
| 383 |
+
"execution_count": null,
|
| 384 |
+
"outputs": []
|
| 385 |
+
}
|
| 386 |
+
],
|
| 387 |
+
"metadata": {
|
| 388 |
+
"kernelspec": {
|
| 389 |
+
"display_name": "Python 3",
|
| 390 |
+
"name": "python3"
|
| 391 |
+
},
|
| 392 |
+
"language_info": {
|
| 393 |
+
"name": "python"
|
| 394 |
+
}
|
| 395 |
+
},
|
| 396 |
+
"nbformat": 4,
|
| 397 |
+
"nbformat_minor": 0
|
| 398 |
+
}
|
submissions_extracted/701/Q3.ipynb
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"# Task 1: Write your code here:\n",
|
| 30 |
+
"data = os.path.join(path, 'Q3_data.csv')\n",
|
| 31 |
+
"data = pd.read_csv(data)\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 |
+
"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 |
+
"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 |
+
"data.describe()"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [
|
| 70 |
+
"data.isnull().sum()"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 1: Write your code here:\n",
|
| 80 |
+
"numerical_cols = data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"for col in numerical_cols:\n",
|
| 83 |
+
" data[col] = data[col].fillna(data[col].mode()[0])\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"data\n",
|
| 86 |
+
"\n"
|
| 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 |
+
"data.duplicated().sum()\n",
|
| 97 |
+
"data.drop_duplicates()"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 3: Write your code here:\n",
|
| 107 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 108 |
+
"categorical_cols = data.select_dtypes(include=[\"object\"]).columns\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"label_encoders = {}\n",
|
| 112 |
+
"for col in categorical_cols:\n",
|
| 113 |
+
" le = LabelEncoder()\n",
|
| 114 |
+
" data[col] = le.fit_transform(data[col])\n",
|
| 115 |
+
" label_encoders[col] = le\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"data"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"\n",
|
| 127 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 128 |
+
"# Task 4: Write your code here:\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"scaler = StandardScaler()\n",
|
| 132 |
+
"data[numerical_cols] = scaler.fit_transform(data[numerical_cols])\n",
|
| 133 |
+
"data.head()\n"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# Task 5: Write your code here:\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"import matplotlib.pyplot as plt\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 147 |
+
"plt.hist(data['Target'].dropna(), bins=30, edgecolor='black')\n",
|
| 148 |
+
"plt.title('Target Distribution')\n",
|
| 149 |
+
"plt.xlabel('Target')\n",
|
| 150 |
+
"plt.ylabel('Frequency')\n",
|
| 151 |
+
"plt.show()"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 1: Write your code here:\n",
|
| 161 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"X = data.drop(\"Target\" , axis=1)\n",
|
| 164 |
+
"y = data[\"Target\"]\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"n_splits = 3 # K=3 Folds\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"pip install catboost"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 187 |
+
"from catboost import CatBoostClassifier\n",
|
| 188 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 189 |
+
"import numpy as np\n",
|
| 190 |
+
"n_splits = 5 # K=3 Folds\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"sr_results = {'loss': [], 'acc': [], 'f1': []}\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"model = CatBoostClassifier(\n",
|
| 197 |
+
" verbose=0,\n",
|
| 198 |
+
" n_estimators=200,\n",
|
| 199 |
+
" max_depth=4\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 |
+
" # Get the train & test split for this fold\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 |
+
"\n",
|
| 210 |
+
" # Fit the model on train data\n",
|
| 211 |
+
" model.fit(X_train, y_train)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" # Use the model to predict the test data\n",
|
| 214 |
+
" y_pred = model.predict(X_test)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Calculate evaluation metrics\n",
|
| 217 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 218 |
+
" f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" sr_results['acc'].append(accuracy)\n",
|
| 221 |
+
" sr_results['f1'].append(f1)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"print(f\" Accuracy: {np.mean(sr_results['acc']):.4f}\")\n",
|
| 224 |
+
"print(f\" F1-Score: {np.mean(sr_results['f1']):.4f}\")"
|
| 225 |
+
],
|
| 226 |
+
"execution_count": null,
|
| 227 |
+
"outputs": []
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "code",
|
| 231 |
+
"metadata": {},
|
| 232 |
+
"source": [
|
| 233 |
+
"# Task 1: Write your code here:\n",
|
| 234 |
+
"importances = {}\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"importances['CatBoost'] = model.feature_importances_\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"# Create a 1x3 plot\n",
|
| 240 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 241 |
+
"axes = axes.flatten()\n",
|
| 242 |
+
"features = X.columns\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 245 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 246 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" ax = axes[i]\n",
|
| 249 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 250 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 251 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"plt.tight_layout()\n",
|
| 254 |
+
"plt.show()"
|
| 255 |
+
],
|
| 256 |
+
"execution_count": null,
|
| 257 |
+
"outputs": []
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"metadata": {},
|
| 262 |
+
"source": [
|
| 263 |
+
"# Task 2: Write your code here:\n",
|
| 264 |
+
"golden_feature = model.feature_importances_\n",
|
| 265 |
+
"print(np.argsort(golden_feature))"
|
| 266 |
+
],
|
| 267 |
+
"execution_count": null,
|
| 268 |
+
"outputs": []
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"cell_type": "code",
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"source": [
|
| 274 |
+
"# Task Bonus: Write your code here:"
|
| 275 |
+
],
|
| 276 |
+
"execution_count": null,
|
| 277 |
+
"outputs": []
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"cell_type": "code",
|
| 281 |
+
"metadata": {},
|
| 282 |
+
"source": [],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
}
|
| 286 |
+
],
|
| 287 |
+
"metadata": {
|
| 288 |
+
"kernelspec": {
|
| 289 |
+
"display_name": "Python 3",
|
| 290 |
+
"name": "python3"
|
| 291 |
+
},
|
| 292 |
+
"language_info": {
|
| 293 |
+
"name": "python"
|
| 294 |
+
}
|
| 295 |
+
},
|
| 296 |
+
"nbformat": 4,
|
| 297 |
+
"nbformat_minor": 0
|
| 298 |
+
}
|
submissions_extracted/702/Q1.ipynb
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"food = os.path.join(path,'Q1_data.csv')\n",
|
| 25 |
+
"df = pd.read_csv(food)"
|
| 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()\n"
|
| 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=10, edgecolor='red')\n",
|
| 69 |
+
"plt.title('delivery_time')\n",
|
| 70 |
+
"plt.xlabel('delivery_time')\n",
|
| 71 |
+
"plt.ylabel('Frequency')\n",
|
| 72 |
+
"plt.show()\n"
|
| 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.drop(\"Order_ID\",inplace=True,axis=1)\n"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 2: Write your code here:\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"# Analyze missing values\n",
|
| 94 |
+
"missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
|
| 95 |
+
"missing_data = pd.DataFrame({\n",
|
| 96 |
+
" 'Column': missing_percentage.index,\n",
|
| 97 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 98 |
+
"})\n",
|
| 99 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 102 |
+
"missing_data.head(10)"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"#completion of task2\n",
|
| 119 |
+
"import numpy as np\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"cat_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 122 |
+
"for col in cat_cols:\n",
|
| 123 |
+
" df[col].fillna(df[col].mode()[0])\n",
|
| 124 |
+
"\n"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 3: Write your code here:\n",
|
| 134 |
+
"# Do we have duplicate samples?\n",
|
| 135 |
+
"def check_duplicates(df):\n",
|
| 136 |
+
" duplicates = df.duplicated().sum()\n",
|
| 137 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 138 |
+
" if duplicates > 0:\n",
|
| 139 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 140 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 141 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 142 |
+
" else:\n",
|
| 143 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"check_duplicates(df)"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 4: Write your code here:\n",
|
| 155 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"label_encoder = LabelEncoder()\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"for col in df.select_dtypes(include=[\"object\"]).columns:\n",
|
| 160 |
+
" df[col] = label_encoder.fit_transform(df[col])"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 5: Write your code here: split x and y\n",
|
| 170 |
+
"X = df.drop(\"Delivery_Time\", axis=1)\n",
|
| 171 |
+
"y = df[\"Delivery_Time\"]\n",
|
| 172 |
+
"scaler = StandardScaler()\n",
|
| 173 |
+
"X_scaled = scaler.fit_transform(X)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"\n"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# Task 6: Write your code here:\n",
|
| 185 |
+
"# Target imbalance means the classes in your target variable are NOT evenly distributed - one class appears WAY more than the other.\n",
|
| 186 |
+
"# Count each class\n",
|
| 187 |
+
"print(y.value_counts())\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"# Show as percentages\n",
|
| 190 |
+
"print(y.value_counts(normalize=True) * 100)"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# Task 1: Write your code here:\n",
|
| 200 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold\n",
|
| 201 |
+
"X_train, X_test, y_train, y_test = X_train, X_test, y_train, y_test = train_test_split(\n",
|
| 202 |
+
" X, y,\n",
|
| 203 |
+
" test_size=0.2,\n",
|
| 204 |
+
" random_state=42,\n",
|
| 205 |
+
" shuffle=True,\n",
|
| 206 |
+
")\n"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 216 |
+
"from sklearn.model_selection import KFold\n",
|
| 217 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 218 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"# K-Fold Cross Validation\n",
|
| 221 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 222 |
+
"mae_scores = []\n",
|
| 223 |
+
"model = RandomForestRegressor()\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"for train_idx, test_idx in kf.split(X_scaled):\n",
|
| 226 |
+
" X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n",
|
| 227 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Train model\n",
|
| 230 |
+
" model.fit(X_train, y_train)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" # Predict\n",
|
| 233 |
+
" y_pred = model.predict(X_test)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Evaluation metrics\n",
|
| 236 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"# Print Evaluation Metrics\n",
|
| 240 |
+
"print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*40)\n",
|
| 241 |
+
"print(f\"MAE : {np.mean(mae_scores):.2f}\")\n",
|
| 242 |
+
"print(\"-\"*40)\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"\n"
|
| 245 |
+
],
|
| 246 |
+
"execution_count": null,
|
| 247 |
+
"outputs": []
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "code",
|
| 251 |
+
"metadata": {},
|
| 252 |
+
"source": [
|
| 253 |
+
"X.info()"
|
| 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 |
+
"\n",
|
| 265 |
+
"feature_cols = [\"Distance_km\",\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\",\"Preparation_Time_min\",\"Courier_Experience_yrs\"]\n",
|
| 266 |
+
"feature_importance = pd.DataFrame({\n",
|
| 267 |
+
" 'feature': feature_cols,\n",
|
| 268 |
+
" 'importance': model.feature_importances_\n",
|
| 269 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 272 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 273 |
+
"plt.xlabel('Importance')\n",
|
| 274 |
+
"plt.title('Feature Importance')\n",
|
| 275 |
+
"plt.gca().invert_yaxis()\n",
|
| 276 |
+
"plt.show()"
|
| 277 |
+
],
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"outputs": []
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"source": [
|
| 285 |
+
"# Task 2: Write your code here:\n",
|
| 286 |
+
"# Histogram\n",
|
| 287 |
+
"plt.hist(y_pred, bins=30)\n",
|
| 288 |
+
"plt.xlabel(\"time\")\n",
|
| 289 |
+
"plt.ylabel(\"Frequency\")\n",
|
| 290 |
+
"plt.title(\"Histogram\")\n",
|
| 291 |
+
"plt.show()"
|
| 292 |
+
],
|
| 293 |
+
"execution_count": null,
|
| 294 |
+
"outputs": []
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"cell_type": "code",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"source": [
|
| 300 |
+
"# Task Bonus: Write your code here:"
|
| 301 |
+
],
|
| 302 |
+
"execution_count": null,
|
| 303 |
+
"outputs": []
|
| 304 |
+
}
|
| 305 |
+
],
|
| 306 |
+
"metadata": {
|
| 307 |
+
"kernelspec": {
|
| 308 |
+
"display_name": "Python 3",
|
| 309 |
+
"name": "python3"
|
| 310 |
+
},
|
| 311 |
+
"language_info": {
|
| 312 |
+
"name": "python"
|
| 313 |
+
}
|
| 314 |
+
},
|
| 315 |
+
"nbformat": 4,
|
| 316 |
+
"nbformat_minor": 0
|
| 317 |
+
}
|
submissions_extracted/702/Q2.ipynb
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# transform to tensors\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 |
+
"\n",
|
| 87 |
+
"# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
|
| 88 |
+
"# Each item in the dataset is returned as (X[i], y[i])\n",
|
| 89 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 90 |
+
"test_dataset = TensorDataset(X_test, y_test)\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 |
+
"# DataLoader for training data\n",
|
| 102 |
+
"train_loader = DataLoader(\n",
|
| 103 |
+
" train_dataset,\n",
|
| 104 |
+
" batch_size=32,\n",
|
| 105 |
+
" shuffle=True,\n",
|
| 106 |
+
" num_workers=2\n",
|
| 107 |
+
")\n",
|
| 108 |
+
"# DataLoader for test/validation data\n",
|
| 109 |
+
"test_loader = DataLoader(\n",
|
| 110 |
+
" test_dataset,\n",
|
| 111 |
+
" batch_size=32,\n",
|
| 112 |
+
" shuffle=False,\n",
|
| 113 |
+
" num_workers=2\n",
|
| 114 |
+
")\n",
|
| 115 |
+
"\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# 4. Print shape of one batch\n",
|
| 125 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 126 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 127 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# 5. Display sample images\n",
|
| 137 |
+
"import matplotlib.pyplot as plt\n",
|
| 138 |
+
"# Get one batch of images and labels\n",
|
| 139 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"# Display the first 6 images in the batch\n",
|
| 142 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"for i in range(6):\n",
|
| 145 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 146 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 147 |
+
" plt.title(f\"Label: {y_batch[i].item()}\")\n",
|
| 148 |
+
" plt.axis('off')\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"plt.tight_layout()\n",
|
| 151 |
+
"plt.show()"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 1: Write your model class here:\n",
|
| 161 |
+
"import torch.nn as nn\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"class NN4Layer(nn.Module):\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 166 |
+
" super(NN4Layer, self).__init__()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 169 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 172 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 175 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 178 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # ReLU activation for non-linearity\n",
|
| 181 |
+
" self.relu = nn.ReLU()\n",
|
| 182 |
+
" # output activation function\n",
|
| 183 |
+
" self.sigmoid = nn.Sigmoid()\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" # Defines how input data flows through the network\n",
|
| 186 |
+
" def forward(self, x):\n",
|
| 187 |
+
" # First hidden layer\n",
|
| 188 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Second hidden layer\n",
|
| 191 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # Third hidden layer\n",
|
| 194 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" # Output layer (raw scores / logits)\n",
|
| 197 |
+
" z = self.layer4(a3)\n",
|
| 198 |
+
" output= self.sigmoid(z)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" return output\n"
|
| 202 |
+
],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"# Task 2: Write your training loop here:\n",
|
| 211 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 212 |
+
" # Set the model to training mode\n",
|
| 213 |
+
" model.train()\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" running_loss = 0.0\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 218 |
+
" # Move batch to the selected device\n",
|
| 219 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 220 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # Forward pass (outputs are logits)\n",
|
| 223 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 224 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # Backward pass & optimization\n",
|
| 227 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 228 |
+
" loss.backward() # Compute gradients\n",
|
| 229 |
+
" optimizer.step() # Update model parameters\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" running_loss += loss.item()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Average loss over all batches\n",
|
| 234 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" return avg_loss\n"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# Task 3: Write your validation loop here:\n",
|
| 246 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 247 |
+
" # Set the model to evaluation mode\n",
|
| 248 |
+
" model.eval()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" running_loss = 0.0\n",
|
| 251 |
+
" correct = 0\n",
|
| 252 |
+
" total = 0\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" with torch.no_grad(): # Disable gradient computation\n",
|
| 255 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 256 |
+
" # Move batch to the selected device\n",
|
| 257 |
+
" X_batch = X_batch.to(device)\n",
|
| 258 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Forward pass\n",
|
| 261 |
+
" outputs = model(X_batch)\n",
|
| 262 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 263 |
+
" running_loss += loss.item()\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Binary predictions\n",
|
| 266 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # Accuracy calculation\n",
|
| 269 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 270 |
+
" total += y_batch.size(0)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 273 |
+
" accuracy = correct / total\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" return avg_loss, accuracy\n"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 285 |
+
"from torch.optim import AdamW\n",
|
| 286 |
+
"import torch.nn as nn\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# Device setup\n",
|
| 289 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Model parameters\n",
|
| 292 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 293 |
+
"hidden_dim = 14 # Design choice\n",
|
| 294 |
+
"# Instantiate model\n",
|
| 295 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"# Print the model architecture\n",
|
| 298 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 299 |
+
"print(model)\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Calculate the total number of trainable parameters\n",
|
| 302 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 303 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"num_epochs = 20\n",
|
| 306 |
+
"learning_rate = 0.001\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 309 |
+
"criterion = nn.MSELoss()\n",
|
| 310 |
+
"# Define optimizer\n",
|
| 311 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n"
|
| 312 |
+
],
|
| 313 |
+
"execution_count": null,
|
| 314 |
+
"outputs": []
|
| 315 |
+
},
|
| 316 |
+
{
|
| 317 |
+
"cell_type": "code",
|
| 318 |
+
"metadata": {},
|
| 319 |
+
"source": [
|
| 320 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 321 |
+
"# Run Training\n",
|
| 322 |
+
"train_losses = []\n",
|
| 323 |
+
"val_losses = []\n",
|
| 324 |
+
"val_accuracies = []\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, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" train_losses.append(train_loss)\n",
|
| 335 |
+
" val_losses.append(val_loss)\n",
|
| 336 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"print('Training Complete!')"
|
| 341 |
+
],
|
| 342 |
+
"execution_count": null,
|
| 343 |
+
"outputs": []
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"cell_type": "code",
|
| 347 |
+
"metadata": {},
|
| 348 |
+
"source": [],
|
| 349 |
+
"execution_count": null,
|
| 350 |
+
"outputs": []
|
| 351 |
+
},
|
| 352 |
+
{
|
| 353 |
+
"cell_type": "code",
|
| 354 |
+
"metadata": {},
|
| 355 |
+
"source": [
|
| 356 |
+
"# Task 1: Write your code here:\n",
|
| 357 |
+
"# Plotting results\n",
|
| 358 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 359 |
+
"\n",
|
| 360 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 361 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 362 |
+
"plt.title('Loss over Epochs')\n",
|
| 363 |
+
"plt.xlabel('Epoch')\n",
|
| 364 |
+
"plt.ylabel('Loss')\n",
|
| 365 |
+
"plt.legend()\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"plt.tight_layout()\n",
|
| 368 |
+
"plt.show()"
|
| 369 |
+
],
|
| 370 |
+
"execution_count": null,
|
| 371 |
+
"outputs": []
|
| 372 |
+
},
|
| 373 |
+
{
|
| 374 |
+
"cell_type": "code",
|
| 375 |
+
"metadata": {},
|
| 376 |
+
"source": [
|
| 377 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 378 |
+
],
|
| 379 |
+
"execution_count": null,
|
| 380 |
+
"outputs": []
|
| 381 |
+
}
|
| 382 |
+
],
|
| 383 |
+
"metadata": {
|
| 384 |
+
"kernelspec": {
|
| 385 |
+
"display_name": "Python 3",
|
| 386 |
+
"name": "python3"
|
| 387 |
+
},
|
| 388 |
+
"language_info": {
|
| 389 |
+
"name": "python"
|
| 390 |
+
}
|
| 391 |
+
},
|
| 392 |
+
"nbformat": 4,
|
| 393 |
+
"nbformat_minor": 0
|
| 394 |
+
}
|
submissions_extracted/702/Q3.ipynb
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"anonymized = os.path.join(path,'Q3_data.csv')\n",
|
| 30 |
+
"df = pd.read_csv(anonymized)"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"# Task 2: Write your code here:\n",
|
| 40 |
+
"df.head()"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 3: Write your code here:\n",
|
| 50 |
+
"df.info()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 4: Write your code here:\n",
|
| 60 |
+
"df.describe()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 1: Write your code here:\n",
|
| 70 |
+
"# Analyze missing values\n",
|
| 71 |
+
"missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
|
| 72 |
+
"missing_data = pd.DataFrame({\n",
|
| 73 |
+
" 'Column': missing_percentage.index,\n",
|
| 74 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 75 |
+
"})\n",
|
| 76 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 79 |
+
"missing_data.head(10)"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"numerical_cols = df.select_dtypes(include=['int64', 'float64']).columns\n",
|
| 89 |
+
"categorical_cols = df.select_dtypes(include=['object']).columns\n",
|
| 90 |
+
"for col in numerical_cols:\n",
|
| 91 |
+
" df[col] = df[col].fillna(df[col].mean()) # Numbers: use mean\n",
|
| 92 |
+
"for col in categorical_cols:\n",
|
| 93 |
+
" df[col] = df[col].fillna(df[col].mode()[0]) # Categories: use mode\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 |
+
"categorical_cols = df.select_dtypes(include=['object']).columns\n",
|
| 104 |
+
"categorical_cols\n",
|
| 105 |
+
"# there is not categorical columns"
|
| 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 |
+
"X = df.drop(\"Target\", axis=1)\n",
|
| 117 |
+
"y = df[\"Target\"]\n",
|
| 118 |
+
"scaler = StandardScaler()\n",
|
| 119 |
+
"X_scaled = scaler.fit_transform(X)"
|
| 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 |
+
"# Target imbalance means the classes in your target variable are NOT evenly distributed - one class appears WAY more than the other.\n",
|
| 130 |
+
"# Count each class\n",
|
| 131 |
+
"print(y.value_counts())\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"# Show as percentages\n",
|
| 134 |
+
"print(y.value_counts(normalize=True) * 100)"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Storage for logistic regression results for each fold\n",
|
| 144 |
+
"lr_accuracy = []\n",
|
| 145 |
+
"lr_f1 = []"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 1,2,3,4,5: Write your code here:\n",
|
| 155 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 156 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 157 |
+
"from catboost import CatBoostClassifier\n",
|
| 158 |
+
"# Use previously generated random classification data\n",
|
| 159 |
+
"model = CatBoostClassifier()\n",
|
| 160 |
+
"# Show full dataset class distribution\n",
|
| 161 |
+
"full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n",
|
| 162 |
+
"print(\"Full Dataset Class Distribution\")\n",
|
| 163 |
+
"print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n",
|
| 164 |
+
"print(\"-\" * 40)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"# Define Stratified K-Fold\n",
|
| 167 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
|
| 172 |
+
" # indexing for each fold\n",
|
| 173 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 174 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" model.fit(X_train, y_train)\n",
|
| 177 |
+
" y_fold_pred = model.predict(X_test)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Calculate evaluation metrics\n",
|
| 180 |
+
" accuracy = accuracy_score(y_test, y_fold_pred)\n",
|
| 181 |
+
" f1 = f1_score(y_test, y_fold_pred, zero_division=0)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # Store results\n",
|
| 184 |
+
" lr_accuracy.append(accuracy)\n",
|
| 185 |
+
" lr_f1.append(f1)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" print(f\"Fold {fold}\")\n",
|
| 188 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 189 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 190 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 191 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # showing class distribution\n",
|
| 194 |
+
" train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
|
| 195 |
+
" test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
|
| 198 |
+
" print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" print(\"-\" * 40)"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"import numpy as np\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n",
|
| 213 |
+
"print(f\" F1-Score: {np.mean(lr_f1):.4f}\")"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Feature importance\n",
|
| 223 |
+
"import matplotlib.pyplot as plt\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"feature_cols = X.select_dtypes(include=['int64', 'float64']).columns\n",
|
| 226 |
+
"feature_importance = pd.DataFrame({\n",
|
| 227 |
+
" 'feature': feature_cols,\n",
|
| 228 |
+
" 'importance': model.feature_importances_\n",
|
| 229 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"plt.figure(figsize=(15, 35))\n",
|
| 232 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 233 |
+
"plt.xlabel('Importance')\n",
|
| 234 |
+
"plt.title('Feature Importance')\n",
|
| 235 |
+
"plt.gca().invert_yaxis()\n",
|
| 236 |
+
"plt.show()"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# Task 2: Write your code here:\n",
|
| 246 |
+
"#The golden feature is P_2 and the second one is D_42."
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task Bonus: Write your code here:"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
}
|
| 260 |
+
],
|
| 261 |
+
"metadata": {
|
| 262 |
+
"kernelspec": {
|
| 263 |
+
"display_name": "Python 3",
|
| 264 |
+
"name": "python3"
|
| 265 |
+
},
|
| 266 |
+
"language_info": {
|
| 267 |
+
"name": "python"
|
| 268 |
+
}
|
| 269 |
+
},
|
| 270 |
+
"nbformat": 4,
|
| 271 |
+
"nbformat_minor": 0
|
| 272 |
+
}
|
submissions_extracted/703/Q1.ipynb
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.model_selection import train_test_split, KFold\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"import warnings\n",
|
| 19 |
+
"warnings.filterwarnings('ignore')\n",
|
| 20 |
+
"\n"
|
| 21 |
+
],
|
| 22 |
+
"execution_count": null,
|
| 23 |
+
"outputs": []
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"metadata": {},
|
| 28 |
+
"source": [
|
| 29 |
+
"import kagglehub\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"# Download latest version\n",
|
| 32 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"print(\"Path to dataset files:\", path)"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# Task 1: Write your code here:\n",
|
| 44 |
+
"# Load the dataset\n",
|
| 45 |
+
"food_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 46 |
+
"df_food = pd.read_csv(food_path)\n",
|
| 47 |
+
"\n"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 2: Write your code here:\n",
|
| 57 |
+
"print(f\"Dataset shape: {df_cars.shape}\")\n",
|
| 58 |
+
"df_food.head()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 3: Write your code here:\n",
|
| 68 |
+
"print(\"DataFrame Info:\")\n",
|
| 69 |
+
"df_food.info()"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 4: Write your code here:\n",
|
| 79 |
+
"print(\"\\nDataFrame Description:\")\n",
|
| 80 |
+
"df_food.describe()"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 5: Write your code here:\n",
|
| 90 |
+
"# 1. What does our target variable (delivery_time) look like?\n",
|
| 91 |
+
"def check_target_distribution(df, target_column):\n",
|
| 92 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 93 |
+
"\n",
|
| 94 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 95 |
+
" plt.xlabel(target_column)\n",
|
| 96 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 97 |
+
" plt.grid(False)\n",
|
| 98 |
+
"\n",
|
| 99 |
+
" plt.show()\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"check_target_distribution(df_food, \"Delivery_Time\")"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"\n",
|
| 111 |
+
"df = df_food.drop([\"Order_ID\"], axis=1)"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# just to Check again data types and structure\n",
|
| 121 |
+
"df_food.info()"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"def check_missing_values(df):\n",
|
| 131 |
+
" missing_values = df.isnull().sum()\n",
|
| 132 |
+
" print(\"Missing Values per Column:\")\n",
|
| 133 |
+
" print(missing_values[missing_values > 0])\n",
|
| 134 |
+
" if missing_values.any():\n",
|
| 135 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 136 |
+
" else:\n",
|
| 137 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"check_missing_values(df_food)"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 3: Write your code here:\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"feature_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n",
|
| 151 |
+
"target_col = 'Delivery_Time'\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"df_clean = df_food.dropna(subset=feature_cols + [target_col]).copy()\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"# Split into X and y\n",
|
| 157 |
+
"X = df_clean[feature_cols]\n",
|
| 158 |
+
"y = df_clean[target_col]\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")\n",
|
| 161 |
+
"print(\"Missing values in y:\", y.isna().sum())\n",
|
| 162 |
+
"print(\"X shape:\", X.shape, \"y shape:\", y.shape)\n"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"# 4. Do we have duplicate samples?\n",
|
| 172 |
+
"def check_duplicates(df):\n",
|
| 173 |
+
" duplicates = df.duplicated().sum()\n",
|
| 174 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 175 |
+
" if duplicates > 0:\n",
|
| 176 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 177 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 178 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 179 |
+
" else:\n",
|
| 180 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"check_duplicates(df_food)"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# 3. Do we have categorical columns?\n",
|
| 192 |
+
"categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"label_encoders = {}\n",
|
| 206 |
+
"for col in categorical_cols:\n",
|
| 207 |
+
" le = LabelEncoder()\n",
|
| 208 |
+
" df_food[col] = le.fit_transform(df_food[col])\n",
|
| 209 |
+
" label_encoders[col] = le\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"df_food"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"# check if Do we have different scales in the data?\n",
|
| 221 |
+
"df_food.describe()"
|
| 222 |
+
],
|
| 223 |
+
"execution_count": null,
|
| 224 |
+
"outputs": []
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"cell_type": "code",
|
| 228 |
+
"metadata": {},
|
| 229 |
+
"source": [
|
| 230 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"numerical_cols = df_food.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"scaler = StandardScaler()\n",
|
| 235 |
+
"df_food[numerical_cols] = scaler.fit_transform(df_food[numerical_cols])\n",
|
| 236 |
+
"df_food.head()\n"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# 1. Is the target imbalanced?\n",
|
| 246 |
+
"import seaborn as sns\n",
|
| 247 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 248 |
+
" print(\"Target Distribution:\")\n",
|
| 249 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 250 |
+
" sns.countplot(x=df[target_column])\n",
|
| 251 |
+
" plt.title(\"Target Distribution\")\n",
|
| 252 |
+
" plt.show()\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"check_target_imbalance(df_food, \"Delivery_Time\")"
|
| 255 |
+
],
|
| 256 |
+
"execution_count": null,
|
| 257 |
+
"outputs": []
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"metadata": {},
|
| 262 |
+
"source": [],
|
| 263 |
+
"execution_count": null,
|
| 264 |
+
"outputs": []
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"cell_type": "code",
|
| 268 |
+
"metadata": {},
|
| 269 |
+
"source": [],
|
| 270 |
+
"execution_count": null,
|
| 271 |
+
"outputs": []
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"cell_type": "code",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"source": [
|
| 277 |
+
"\n",
|
| 278 |
+
"df_clean = df_food.dropna().copy()\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1)\n",
|
| 282 |
+
"y = df_clean[\"Delivery_Time\"]\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"# Split the dataset into training and testing sets (80% train, 20% test)\n",
|
| 285 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"print(\"NaNs in y_train:\", y_train.isna().sum())\n",
|
| 289 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n"
|
| 290 |
+
],
|
| 291 |
+
"execution_count": null,
|
| 292 |
+
"outputs": []
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"cell_type": "code",
|
| 296 |
+
"metadata": {},
|
| 297 |
+
"source": [
|
| 298 |
+
"# Train Random Forest Regressor\n",
|
| 299 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 300 |
+
"model.fit(X_train, y_train)\n",
|
| 301 |
+
"print(\"Model trained!\")"
|
| 302 |
+
],
|
| 303 |
+
"execution_count": null,
|
| 304 |
+
"outputs": []
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"# Predict and evaluate\n",
|
| 311 |
+
"y_pred = model.predict(X_test)\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"print(f\"MAE: ${mae:,.2f}\")\n"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"\n",
|
| 325 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"mae_scores = []\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"for train_idx, val_idx in kfold.split(X_train):\n",
|
| 330 |
+
"\n",
|
| 331 |
+
" X_fold_train = X_train.iloc[train_idx]\n",
|
| 332 |
+
" X_fold_val = X_train.iloc[val_idx]\n",
|
| 333 |
+
" y_fold_train = y_train.iloc[train_idx]\n",
|
| 334 |
+
" y_fold_val = y_train.iloc[val_idx]\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" # Train and predict\n",
|
| 337 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 338 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" # Calculate metrics\n",
|
| 341 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"print(\"5-Fold CV Results:\")\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"print(f\"Average MAE across all folds: {mae_scores.mean():.2f}\")\n"
|
| 348 |
+
],
|
| 349 |
+
"execution_count": null,
|
| 350 |
+
"outputs": []
|
| 351 |
+
},
|
| 352 |
+
{
|
| 353 |
+
"cell_type": "code",
|
| 354 |
+
"metadata": {},
|
| 355 |
+
"source": [
|
| 356 |
+
"\n"
|
| 357 |
+
],
|
| 358 |
+
"execution_count": null,
|
| 359 |
+
"outputs": []
|
| 360 |
+
},
|
| 361 |
+
{
|
| 362 |
+
"cell_type": "code",
|
| 363 |
+
"metadata": {},
|
| 364 |
+
"source": [
|
| 365 |
+
"# Task 1: Write your code here:\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"# Feature importance\n",
|
| 368 |
+
"feature_importance = pd.DataFrame({\n",
|
| 369 |
+
" 'feature': X_train.columns,\n",
|
| 370 |
+
" 'importance': model.feature_importances_\n",
|
| 371 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"# Plot\n",
|
| 374 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 375 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 376 |
+
"plt.xlabel('Importance')\n",
|
| 377 |
+
"plt.title('Feature Importance')\n",
|
| 378 |
+
"plt.gca().invert_yaxis()\n",
|
| 379 |
+
"plt.show()\n"
|
| 380 |
+
],
|
| 381 |
+
"execution_count": null,
|
| 382 |
+
"outputs": []
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"cell_type": "code",
|
| 386 |
+
"metadata": {},
|
| 387 |
+
"source": [
|
| 388 |
+
"# Delivery_Time distribution\n",
|
| 389 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 390 |
+
"plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black', color='green')\n",
|
| 391 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 392 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 393 |
+
"plt.ylabel('Frequency')\n",
|
| 394 |
+
"plt.show()"
|
| 395 |
+
],
|
| 396 |
+
"execution_count": null,
|
| 397 |
+
"outputs": []
|
| 398 |
+
},
|
| 399 |
+
{
|
| 400 |
+
"cell_type": "code",
|
| 401 |
+
"metadata": {},
|
| 402 |
+
"source": [
|
| 403 |
+
"# Task Bonus: Write your code here:"
|
| 404 |
+
],
|
| 405 |
+
"execution_count": null,
|
| 406 |
+
"outputs": []
|
| 407 |
+
}
|
| 408 |
+
],
|
| 409 |
+
"metadata": {
|
| 410 |
+
"kernelspec": {
|
| 411 |
+
"display_name": "Python 3",
|
| 412 |
+
"name": "python3"
|
| 413 |
+
},
|
| 414 |
+
"language_info": {
|
| 415 |
+
"name": "python"
|
| 416 |
+
}
|
| 417 |
+
},
|
| 418 |
+
"nbformat": 4,
|
| 419 |
+
"nbformat_minor": 0
|
| 420 |
+
}
|
submissions_extracted/703/Q2.ipynb
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
"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 |
+
"from torch.utils.data import DataLoader, TensorDataset\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 |
+
"\n"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# 2. Create TensorDataset objects\n",
|
| 86 |
+
"# Create TensorDatasets for training and testing\n",
|
| 87 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 88 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# 3. Create DataLoaders\n",
|
| 98 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 99 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 100 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"\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 |
+
"# Get the first batch from the training DataLoader\n",
|
| 114 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 115 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 116 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 117 |
+
"\n"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# 5. Display sample images\n",
|
| 127 |
+
"import matplotlib.pyplot as plt\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"# Number of images to display\n",
|
| 130 |
+
"num_images = 6\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"plt.figure(figsize=(12, 4))\n",
|
| 133 |
+
"for i in range(num_images):\n",
|
| 134 |
+
" plt.subplot(1, num_images, i + 1)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
" img = X_batch[i].permute(1, 2, 0)\n",
|
| 137 |
+
"\n",
|
| 138 |
+
" plt.imshow(img)\n",
|
| 139 |
+
" plt.title(f\"Label: {y_batch[i].item()}\")\n",
|
| 140 |
+
" plt.axis(\"off\")\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"plt.tight_layout()\n",
|
| 143 |
+
"plt.show()\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"\n"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 1: Write your model class here:\n",
|
| 155 |
+
"import torch.nn as nn\n",
|
| 156 |
+
"class NN4Layer(nn.Module):\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 159 |
+
" super(NN4Layer, self).__init__()\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 162 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 165 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 168 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 171 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # activation function for non-linearity\n",
|
| 174 |
+
" self.relu = nn.ReLU()\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Defines how input data flows through the network\n",
|
| 177 |
+
" def forward(self, x):\n",
|
| 178 |
+
" # Layer 1: TODO\n",
|
| 179 |
+
" z1 = self.layer1(x)\n",
|
| 180 |
+
" a1 = self.relu(z1)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # Layer 2 TODO\n",
|
| 183 |
+
" z2 = self.layer2(a1)\n",
|
| 184 |
+
" a2 = self.relu(z2)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Layer 3 TODO\n",
|
| 187 |
+
" z3 = self.layer3(a2)\n",
|
| 188 |
+
" a3 = self.relu(z3)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" # Output layer TODO\n",
|
| 192 |
+
" z4 = self.layer4(a3)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" return z4"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# Task 2: Write your training loop here:\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 208 |
+
" # Set the model to training mode\n",
|
| 209 |
+
" model.train()\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" running_loss = 0.0\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 214 |
+
" # Move batch to the selected device\n",
|
| 215 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 216 |
+
" y_batch = y_batch.to(device)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" # Forward pass\n",
|
| 219 |
+
" # TODO: make predictions\n",
|
| 220 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 221 |
+
" # TODO: compute loss\n",
|
| 222 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" # Backward pass & optimization\n",
|
| 225 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 226 |
+
" loss.backward() # Compute gradients\n",
|
| 227 |
+
" optimizer.step() # Update model parameters\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" running_loss += loss.item()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Average loss over all batches\n",
|
| 232 |
+
" avg_loss = running_loss / len(train_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 3: Write your validation loop here:\n",
|
| 244 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 245 |
+
" def validate(model, criterion, test_loader, device):\n",
|
| 246 |
+
" # Set the model to evaluation mode\n",
|
| 247 |
+
" model.eval()\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" running_loss = 0.0\n",
|
| 250 |
+
" correct = 0\n",
|
| 251 |
+
" total = 0\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" with torch.no_grad():\n",
|
| 254 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 255 |
+
" # Move data to device\n",
|
| 256 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 257 |
+
" y_batch = y_batch.to(device)\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # Forward pass\n",
|
| 260 |
+
" # : make predictions\n",
|
| 261 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 262 |
+
" # : compute loss\n",
|
| 263 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 264 |
+
" running_loss += loss.item()\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" # : Apply Softmax to get probabilities\n",
|
| 267 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" # : Multiclass predictions\n",
|
| 270 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" # Accuracy calculation\n",
|
| 273 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 274 |
+
" total += y_batch.size(0)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 277 |
+
" : how do we calculate accuracy?\n",
|
| 278 |
+
" accuracy = correct / total\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" return avg_loss, accuracy\n"
|
| 281 |
+
],
|
| 282 |
+
"execution_count": null,
|
| 283 |
+
"outputs": []
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"cell_type": "code",
|
| 287 |
+
"metadata": {},
|
| 288 |
+
"source": [
|
| 289 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 290 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
|
| 291 |
+
],
|
| 292 |
+
"execution_count": null,
|
| 293 |
+
"outputs": []
|
| 294 |
+
},
|
| 295 |
+
{
|
| 296 |
+
"cell_type": "code",
|
| 297 |
+
"metadata": {},
|
| 298 |
+
"source": [
|
| 299 |
+
"\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Model parameters\n",
|
| 302 |
+
"# : What are input features ? (hint: flatten using channel, height, width)\n",
|
| 303 |
+
"input_dim = 3 * 36 * 36 # CIFAR-10 images flattened (RGB)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# : choose number of hidden neurons\n",
|
| 306 |
+
"hidden_dim = 64 # Design choice\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# : what are the number of classes ?\n",
|
| 309 |
+
"output_dim = 10 # CIFAR-10 classes\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"# : Instantiate model (what are the model class inputs?)\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 |
+
],
|
| 322 |
+
"execution_count": null,
|
| 323 |
+
"outputs": []
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"cell_type": "code",
|
| 327 |
+
"metadata": {},
|
| 328 |
+
"source": [
|
| 329 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 330 |
+
"# its a Hyperparameters so no problem to feel free to experiment\n",
|
| 331 |
+
"num_epochs = 20\n",
|
| 332 |
+
"learning_rate = 0.001"
|
| 333 |
+
],
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"outputs": []
|
| 336 |
+
},
|
| 337 |
+
{
|
| 338 |
+
"cell_type": "code",
|
| 339 |
+
"metadata": {},
|
| 340 |
+
"source": [
|
| 341 |
+
"# Define criterion (loss function)\n",
|
| 342 |
+
"from torch.optim import AdamW\n",
|
| 343 |
+
"criterion = nn.MSELoss()\n",
|
| 344 |
+
"# Define optimizer\n",
|
| 345 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
},
|
| 350 |
+
{
|
| 351 |
+
"cell_type": "code",
|
| 352 |
+
"metadata": {},
|
| 353 |
+
"source": [
|
| 354 |
+
"# Run Training\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 |
+
"\n",
|
| 366 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 367 |
+
" val_loss = val_loss if val_loss is not None else 0.0\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"\n",
|
| 371 |
+
"\n",
|
| 372 |
+
" train_losses.append(train_loss)\n",
|
| 373 |
+
" val_losses.append(val_loss)\n",
|
| 374 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"print('Training Complete!')\n",
|
| 379 |
+
"\n"
|
| 380 |
+
],
|
| 381 |
+
"execution_count": null,
|
| 382 |
+
"outputs": []
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"cell_type": "code",
|
| 386 |
+
"metadata": {},
|
| 387 |
+
"source": [
|
| 388 |
+
"# Task 1: Write your code here:\n",
|
| 389 |
+
"# Plotting results\n",
|
| 390 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 391 |
+
"\n",
|
| 392 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 393 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 394 |
+
"plt.title('Loss over Epochs')\n",
|
| 395 |
+
"plt.xlabel('Epoch')\n",
|
| 396 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 397 |
+
"plt.legend()\n",
|
| 398 |
+
"\n",
|
| 399 |
+
"plt.tight_layout()\n",
|
| 400 |
+
"plt.show()"
|
| 401 |
+
],
|
| 402 |
+
"execution_count": null,
|
| 403 |
+
"outputs": []
|
| 404 |
+
},
|
| 405 |
+
{
|
| 406 |
+
"cell_type": "code",
|
| 407 |
+
"metadata": {},
|
| 408 |
+
"source": [
|
| 409 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 410 |
+
],
|
| 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/703/Q3.ipynb
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"
|
| 11 |
+
],
|
| 12 |
+
"execution_count": null,
|
| 13 |
+
"outputs": []
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "code",
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"source": [
|
| 19 |
+
"import kagglehub\n",
|
| 20 |
+
"\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:\n",
|
| 39 |
+
"# Load the CSV file\n",
|
| 40 |
+
"df_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 41 |
+
"df = pd.read_csv(df_path)"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"# Task 2:\n",
|
| 51 |
+
"#Inspect the first few rows\n",
|
| 52 |
+
"print(f\"Shape: {df.shape}\")\n",
|
| 53 |
+
"df.head()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 3:\n",
|
| 63 |
+
"# Display dataset information\n",
|
| 64 |
+
"df.info()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"# Task 4:\n",
|
| 74 |
+
"# Descriptive statistics for numerical columns\n",
|
| 75 |
+
"df.describe()"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# Task 1:\n",
|
| 85 |
+
"def check_missing_values(df):\n",
|
| 86 |
+
" missing_values = df.isnull().sum()\n",
|
| 87 |
+
" print(\"Missing Values per Column:\")\n",
|
| 88 |
+
" print(missing_values[missing_values > 0])\n",
|
| 89 |
+
" if missing_values.any():\n",
|
| 90 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 91 |
+
" else:\n",
|
| 92 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"check_missing_values(df)\n",
|
| 95 |
+
"df['Target'].value_counts()\n"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# Task 2:\n",
|
| 105 |
+
"# Do we have duplicate samples?\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)\n"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 3:\n",
|
| 126 |
+
"from sklearn.preprocessing import LabelEncoder , StandardScaler\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"label_encoders = {}\n",
|
| 129 |
+
"for col in categorical_cols:\n",
|
| 130 |
+
" le = LabelEncoder()\n",
|
| 131 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 132 |
+
" label_encoders[col] = le\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"df"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 4:\n",
|
| 144 |
+
"scaler = StandardScaler()\n",
|
| 145 |
+
"df = scaler.fit_transform(df)\n",
|
| 146 |
+
"df.head()"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"# Task 5:\n",
|
| 156 |
+
"import seaborn as sns\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 |
+
"# Task 1:\n",
|
| 175 |
+
"# Split the dataset into features (X) and target (y)\n",
|
| 176 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 177 |
+
"y = df_clean['Delivery_Time'].astype(float)"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 187 |
+
"# Task 2,3,4,5:\n",
|
| 188 |
+
"from sklearn.model_selection import KFold\n",
|
| 189 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 190 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"# Use the correct split: KFold\n",
|
| 193 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 196 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"# Storage for linear regression results for each fold\n",
|
| 199 |
+
"lr_losses = []\n",
|
| 200 |
+
"lr_mse = []\n",
|
| 201 |
+
"lr_rmse = []\n",
|
| 202 |
+
"lr_r2 = []\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 205 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 208 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Train\n",
|
| 211 |
+
" model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 212 |
+
" class_weight='balanced', random_state=42)\n",
|
| 213 |
+
" model.fit(X_train, y_train)\n",
|
| 214 |
+
" print(\"Model trained!\")\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Validate\n",
|
| 217 |
+
" # Predictions and metrics\n",
|
| 218 |
+
" y_pred = model.predict(X_test)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Calculate evaluation metrics\n",
|
| 221 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 222 |
+
" rmse = np.sqrt(mse)\n",
|
| 223 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Store results\n",
|
| 226 |
+
" lr_mse.append(mse)\n",
|
| 227 |
+
" lr_rmse.append(rmse)\n",
|
| 228 |
+
" lr_r2.append(r2)\n"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 1: Write your code here:\n",
|
| 238 |
+
"# Task 1:\n",
|
| 239 |
+
"# Plot for the feature importance from your trained model\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"# Define features and target\n",
|
| 242 |
+
"importance = pd.DataFrame({\n",
|
| 243 |
+
" 'feature': X.columns,\n",
|
| 244 |
+
" 'importance': model.feature_importances_\n",
|
| 245 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 248 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 249 |
+
"plt.xlabel('Importance')\n",
|
| 250 |
+
"plt.title('Feature Importance')\n",
|
| 251 |
+
"plt.gca().invert_yaxis()\n",
|
| 252 |
+
"plt.show()"
|
| 253 |
+
],
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"outputs": []
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"metadata": {},
|
| 260 |
+
"source": [
|
| 261 |
+
"# Task 2: Write your code here:\n",
|
| 262 |
+
"# Task 2:\n",
|
| 263 |
+
"# Plot predicted delivery time histogram\n",
|
| 264 |
+
"plt.hist(y_pred, bins=30, edgecolor='black')\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"plt.title(\"Predicted Target Distribution\")\n",
|
| 267 |
+
"plt.xlabel(\"Predicted Value\")\n",
|
| 268 |
+
"plt.ylabel(\"Frequency\")\n",
|
| 269 |
+
"plt.grid(False)\n",
|
| 270 |
+
"plt.show()"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "code",
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"source": [
|
| 279 |
+
"# Task Bonus: Write your code here:"
|
| 280 |
+
],
|
| 281 |
+
"execution_count": null,
|
| 282 |
+
"outputs": []
|
| 283 |
+
}
|
| 284 |
+
],
|
| 285 |
+
"metadata": {
|
| 286 |
+
"kernelspec": {
|
| 287 |
+
"display_name": "Python 3",
|
| 288 |
+
"name": "python3"
|
| 289 |
+
},
|
| 290 |
+
"language_info": {
|
| 291 |
+
"name": "python"
|
| 292 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import numpy as np\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score , mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 18 |
+
"import warnings\n",
|
| 19 |
+
"warnings.filterwarnings('ignore')\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"# Download latest version\n",
|
| 23 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"print(\"Path to dataset files:\", path)"
|
| 26 |
+
],
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"outputs": []
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"metadata": {},
|
| 33 |
+
"source": [
|
| 34 |
+
"# Task 1: Write your code here:\n",
|
| 35 |
+
"rest_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 36 |
+
"df_rest = pd.read_csv(rest_path)\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"print(f\"Dataset shape: {df_rest.shape}\")"
|
| 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_rest.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_rest.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_rest.describe()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 5: Write your code here:\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# delivery_time (target variable)\n",
|
| 80 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 81 |
+
"plt.hist(df_rest['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 82 |
+
"plt.title('Delivery Time Plot')\n",
|
| 83 |
+
"plt.xlabel('time')\n",
|
| 84 |
+
"plt.ylabel('Frequency')\n",
|
| 85 |
+
"plt.show()"
|
| 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_rest= df_rest.drop(columns=['Order_ID'], axis=1)\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"df_rest.info()"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 2: Write your code here:\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# the columns that has missing values :\n",
|
| 109 |
+
"# 1. Weather 2. Traffic_Level 3. Time_of_Day 4. Courier_Experience_yrs 5. Delivery_Time\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Fill with mode (categorical) 1. Weather 2. Traffic_Level 3. Time_of_Day\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"print(\"\\n\\n -------- Fill with mode: --------\\n\")\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"df_mode = df_rest.copy()\n",
|
| 117 |
+
"df_mode['Weather'] = df_mode['Weather'].fillna(df_mode['Weather'].mode()[0])\n",
|
| 118 |
+
"df_mode['Traffic_Level'] = df_mode['Traffic_Level'].fillna(df_mode['Traffic_Level'].mode()[0])\n",
|
| 119 |
+
"df_mode['Time_of_Day'] = df_mode['Time_of_Day'].fillna(df_mode['Time_of_Day'].mode()[0])\n",
|
| 120 |
+
"print(df_mode)\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# Fill with mean/median (numerical) 1. Courier_Experience_yrs 2. Delivery_Time\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"print(\"\\n\\n -------- Fill with mean/median: --------\\n\")\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"df_mean = df_mode.copy()\n",
|
| 128 |
+
"df_mean['Delivery_Time'] = df_mean['Delivery_Time'].fillna(df_mean['Delivery_Time'].mean())\n",
|
| 129 |
+
"df_mean['Courier_Experience_yrs'] = df_mean['Courier_Experience_yrs'].fillna(df_mean['Courier_Experience_yrs'].median())\n",
|
| 130 |
+
"print(df_mean)\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"df_clean = df_mean.copy()\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"print(\"\\n\\n -------- Final clean dataset check up --------\\n\")\n",
|
| 135 |
+
"df_clean.info()"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 3: Write your code here:\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"df = df_clean.drop_duplicates()\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"df.info()\n"
|
| 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 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Categorical Columns: ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"label_encoders = {}\n",
|
| 172 |
+
"for col in categorical_cols:\n",
|
| 173 |
+
" le = LabelEncoder()\n",
|
| 174 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 175 |
+
" label_encoders[col] = le\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"df\n"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"scaler = StandardScaler()\n",
|
| 189 |
+
"scaled = scaler.fit_transform(df)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"print(\"Original:\\n\", df)\n",
|
| 192 |
+
"print(\"\\nScaled (mean ≈ 0, std ≈ 1):\\n\", scaled)\n",
|
| 193 |
+
"print(\"\\nMeans:\", scaled.mean(axis=0))\n",
|
| 194 |
+
"print(\"Stds:\", scaled.std(axis=0))\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"df.head()"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 208 |
+
" print(\"Target Distribution:\")\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 211 |
+
" plt.show()\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"check_target_imbalance(df, \"Delivery_Time\")\n",
|
| 215 |
+
"print(\"\\nTarget is imbalnce as we observe from the Histogram\")"
|
| 216 |
+
],
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"outputs": []
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"# Task 1: Write your code here:\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 227 |
+
"y = df[\"Delivery_Time\"].astype(float)\n",
|
| 228 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# # Task 2,3,4,5: Write your code here:\n",
|
| 238 |
+
"from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"# model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 241 |
+
"# model.fit(X_train, y_train)\n",
|
| 242 |
+
"# print(\"Model trained!\")\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"# kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"# mae_scores = []\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"# for train_idx, val_idx in kfold.split(X_train):\n",
|
| 249 |
+
"# X_train, X_test = X_train[train_idx], X_train[val_idx]\n",
|
| 250 |
+
"# y_train, y_pred = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"# # Train and predict\n",
|
| 253 |
+
"# model.fit(X_train, y_train)\n",
|
| 254 |
+
"# y_fold_pred = model.predict(X_test)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"# # Calculate metrics\n",
|
| 257 |
+
"# mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"# mae_scores = np.array(mae_scores)\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"# print(f\"5-Fold CV Results:\")\n",
|
| 262 |
+
"# print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n",
|
| 268 |
+
"rf.fit(X_train, y_train)\n",
|
| 269 |
+
"y_pred = rf.predict(X_test)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"# Evaluate using MAE (Mean Absolute Error) ONLY\n",
|
| 272 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 273 |
+
"print(f\"MAE: {mae:.2f}\")\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"# Print the averaged score across all folds"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"# Task 1: Write your code here:\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"feature_cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"importance = pd.DataFrame({\n",
|
| 289 |
+
" 'feature': feature_cols,\n",
|
| 290 |
+
" 'importance': rf.feature_importances_\n",
|
| 291 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 294 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 295 |
+
"plt.xlabel('Importance')\n",
|
| 296 |
+
"plt.title('Feature Importance')\n",
|
| 297 |
+
"plt.gca().invert_yaxis()\n",
|
| 298 |
+
"plt.show()"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"# Task 2: Write your code here:\n",
|
| 308 |
+
"# delivery_time (target variable)\n",
|
| 309 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 310 |
+
"plt.hist(y_pred, bins=50, edgecolor='black')\n",
|
| 311 |
+
"plt.title('Delivery Time Plot')\n",
|
| 312 |
+
"plt.xlabel('time')\n",
|
| 313 |
+
"plt.ylabel('Frequency')\n",
|
| 314 |
+
"plt.show()"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Task 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/704/Q2.ipynb
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"from torchvision.datasets import MNIST\n",
|
| 72 |
+
"from torch.utils.data import DataLoader\n",
|
| 73 |
+
"from torch.optim import Adam\n",
|
| 74 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 75 |
+
"import torch.nn.functional as F\n",
|
| 76 |
+
"import matplotlib.pyplot as plt\n",
|
| 77 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 78 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 79 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 80 |
+
"from torch.utils.data import TensorDataset\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 83 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 86 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n"
|
| 87 |
+
],
|
| 88 |
+
"execution_count": null,
|
| 89 |
+
"outputs": []
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "code",
|
| 93 |
+
"metadata": {},
|
| 94 |
+
"source": [
|
| 95 |
+
"# 2. Create TensorDataset objects\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"train_dataset = MNIST(\n",
|
| 98 |
+
" root='./datasets', # Dataset storage path\n",
|
| 99 |
+
" train=True, # Use training data\n",
|
| 100 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 101 |
+
" download=True # Download if not available\n",
|
| 102 |
+
")\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"# Testing dataset\n",
|
| 105 |
+
"test_dataset = MNIST(\n",
|
| 106 |
+
" root='./datasets', # Dataset storage path\n",
|
| 107 |
+
" train=False, # Use test data\n",
|
| 108 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 109 |
+
" download=True # Download if not available\n",
|
| 110 |
+
")\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
|
| 113 |
+
"test_dataset = TensorDataset(X_test_tensor, y_test_tensor)"
|
| 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 |
+
"train_loader = DataLoader(\n",
|
| 125 |
+
" train_dataset,\n",
|
| 126 |
+
" batch_size=32,\n",
|
| 127 |
+
" shuffle=True,\n",
|
| 128 |
+
" num_workers=2\n",
|
| 129 |
+
")\n",
|
| 130 |
+
"# DataLoader for test/validation data\n",
|
| 131 |
+
"test_loader = DataLoader(\n",
|
| 132 |
+
" test_dataset,\n",
|
| 133 |
+
" batch_size=32,\n",
|
| 134 |
+
" shuffle=False,\n",
|
| 135 |
+
" num_workers=2\n",
|
| 136 |
+
")\n",
|
| 137 |
+
"\n"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# 4. Print shape of one batch\n",
|
| 147 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 148 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 149 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# 5. Display sample images\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"# Get one batch of images and labels\n",
|
| 161 |
+
"images, labels = next(iter(train_loader))\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"# Display the first 6 images in the batch\n",
|
| 164 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"for i in range(6):\n",
|
| 167 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 168 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 169 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 170 |
+
" plt.axis('off')\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"plt.tight_layout()\n",
|
| 173 |
+
"plt.show()"
|
| 174 |
+
],
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"outputs": []
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "code",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"source": [
|
| 182 |
+
"# Task 1: Write your model class here:\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"class NN4Layer(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 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # activation function for non-linearity\n",
|
| 201 |
+
" self.relu = nn.ReLU()\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" def forward(self, x):\n",
|
| 204 |
+
" # Layer 1\n",
|
| 205 |
+
" z1 = self.layer1(x)\n",
|
| 206 |
+
" a1 = self.relu(z1)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Layer 2\n",
|
| 209 |
+
" z2 = self.layer2(a1)\n",
|
| 210 |
+
" a2 = self.relu(z2)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" # Layer 3\n",
|
| 213 |
+
" z3 = self.layer3(a2)\n",
|
| 214 |
+
" a3 = self.relu(z3)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Layer 4\n",
|
| 217 |
+
" z4 = self.layer4(a3)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" return z4"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 2: Write your training loop here:\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 232 |
+
" # Set the model to training mode\n",
|
| 233 |
+
" model.train()\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" running_loss = 0.0\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 238 |
+
" # Move batch to the selected device\n",
|
| 239 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).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, 10)\n",
|
| 244 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" # Backward pass & optimization\n",
|
| 247 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 248 |
+
" loss.backward() # Compute gradients\n",
|
| 249 |
+
" optimizer.step() # Update model parameters\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" running_loss += loss.item()\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Average loss over all batches\n",
|
| 254 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" return avg_loss"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task 3: Write your validation loop here:\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 268 |
+
" # Set the model to evaluation mode\n",
|
| 269 |
+
" model.eval()\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" running_loss = 0.0\n",
|
| 272 |
+
" correct = 0\n",
|
| 273 |
+
" total = 0\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" with torch.no_grad():\n",
|
| 276 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 277 |
+
" # Move data to device\n",
|
| 278 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 279 |
+
" y_batch = y_batch.to(device)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" # Forward pass\n",
|
| 282 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 283 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 284 |
+
" running_loss += loss.item()\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" # Apply Softmax to get probabilities\n",
|
| 287 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" # Multiclass predictions\n",
|
| 290 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" # Accuracy calculation\n",
|
| 293 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 294 |
+
" total += y_batch.size(0)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 297 |
+
" accuracy = correct / total\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" return avg_loss, accuracy"
|
| 300 |
+
],
|
| 301 |
+
"execution_count": null,
|
| 302 |
+
"outputs": []
|
| 303 |
+
},
|
| 304 |
+
{
|
| 305 |
+
"cell_type": "code",
|
| 306 |
+
"metadata": {},
|
| 307 |
+
"source": [
|
| 308 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 311 |
+
"model = NN4Layer(self, input_dim, hidden_dim, output_dim).to(device)\n",
|
| 312 |
+
"loss = criterion(X_hat, X_batch)\n",
|
| 313 |
+
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n",
|
| 314 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"# Loop\n",
|
| 317 |
+
"for epoch in range(10):\n",
|
| 318 |
+
" train_loss = train_step(model, train_loader, criterion, optimizer)\n",
|
| 319 |
+
" val_loss = validate_step(model, test_loader, criterion)\n",
|
| 320 |
+
" print(f\"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}\")"
|
| 321 |
+
],
|
| 322 |
+
"execution_count": null,
|
| 323 |
+
"outputs": []
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"cell_type": "code",
|
| 327 |
+
"metadata": {},
|
| 328 |
+
"source": [
|
| 329 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 330 |
+
"num_epochs = 20\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"# Model parameters\n",
|
| 333 |
+
"input_dim = 28 * 28 # MNIST images flattened\n",
|
| 334 |
+
"hidden_dim = 14 # Design choice\n",
|
| 335 |
+
"output_dim = 10 # Digits 0–9\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"# Instantiate model\n",
|
| 338 |
+
"model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"# Print the model architecture\n",
|
| 341 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 342 |
+
"print(model)\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"# Calculate the total number of trainable parameters\n",
|
| 345 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 346 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 347 |
+
],
|
| 348 |
+
"execution_count": null,
|
| 349 |
+
"outputs": []
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"cell_type": "code",
|
| 353 |
+
"metadata": {},
|
| 354 |
+
"source": [
|
| 355 |
+
"# Task 1: Write your code here:"
|
| 356 |
+
],
|
| 357 |
+
"execution_count": null,
|
| 358 |
+
"outputs": []
|
| 359 |
+
},
|
| 360 |
+
{
|
| 361 |
+
"cell_type": "code",
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"source": [
|
| 364 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 365 |
+
],
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"outputs": []
|
| 368 |
+
}
|
| 369 |
+
],
|
| 370 |
+
"metadata": {
|
| 371 |
+
"kernelspec": {
|
| 372 |
+
"display_name": "Python 3",
|
| 373 |
+
"name": "python3"
|
| 374 |
+
},
|
| 375 |
+
"language_info": {
|
| 376 |
+
"name": "python"
|
| 377 |
+
}
|
| 378 |
+
},
|
| 379 |
+
"nbformat": 4,
|
| 380 |
+
"nbformat_minor": 0
|
| 381 |
+
}
|
submissions_extracted/704/Q3.ipynb
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import kagglehub\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\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 RandomForestRegressor\n",
|
| 17 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score , mean_absolute_error, mean_squared_error\n",
|
| 18 |
+
"from sklearn.model_selection import StratifiedKFold\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 |
+
"x = os.path.join(path, 'Q3_data.csv')\n",
|
| 40 |
+
"df = pd.read_csv(x)\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"print(f\"Dataset shape: {df.shape}\")"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 2: Write your code here:\n",
|
| 52 |
+
"df.head()"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 3: Write your code here:\n",
|
| 62 |
+
"df.info()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 4: Write your code here:\n",
|
| 72 |
+
"df.describe()"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 1: Write your code here:"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# Task 2: Write your code here:"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 3: Write your code here:"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 4: Write your code here:"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# Task 5: Write your code here:"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# Task 1: Write your code here:"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 1: Write your code here:"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 2: Write your code here:"
|
| 154 |
+
],
|
| 155 |
+
"execution_count": null,
|
| 156 |
+
"outputs": []
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"source": [
|
| 162 |
+
"# Task Bonus: Write your code here:"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
}
|
| 167 |
+
],
|
| 168 |
+
"metadata": {
|
| 169 |
+
"kernelspec": {
|
| 170 |
+
"display_name": "Python 3",
|
| 171 |
+
"name": "python3"
|
| 172 |
+
},
|
| 173 |
+
"language_info": {
|
| 174 |
+
"name": "python"
|
| 175 |
+
}
|
| 176 |
+
},
|
| 177 |
+
"nbformat": 4,
|
| 178 |
+
"nbformat_minor": 0
|
| 179 |
+
}
|
submissions_extracted/705/Q1.ipynb
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"# Download latest version\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"print(\"Path to dataset files:\", path)"
|
| 16 |
+
],
|
| 17 |
+
"execution_count": null,
|
| 18 |
+
"outputs": []
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"cell_type": "code",
|
| 22 |
+
"metadata": {},
|
| 23 |
+
"source": [
|
| 24 |
+
"# Task 1: Write your code here:\n",
|
| 25 |
+
"#import pandas as pd\n",
|
| 26 |
+
"#import os\n",
|
| 27 |
+
"cars_path =os.path.join(path, 'ANON_OWNER/q1-exam-data.csv')\n",
|
| 28 |
+
"df_cars =pd.read_csv(cars_path)\n",
|
| 29 |
+
"print(f\"Dataset shape: {df_cars.shape}\")\n",
|
| 30 |
+
"df_cars.head()"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"# Task 2: Write your code here:\n",
|
| 40 |
+
"df_cars.head()"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 3: Write your code here:"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 4: Write your code here:"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 5: Write your code here:"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# Task 1: Write your code here:"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 2: Write your code here:"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 3: Write your code here:"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 4: Write your code here:"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 5: Write your code here:"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 6: 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/705/Q2.ipynb
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
| 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/705/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/706/Q1.ipynb
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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",
|
| 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:import pandas as pd\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"df = pd.read_csv(csv_path)\n",
|
| 43 |
+
"\n"
|
| 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 5: Write your code here:\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"def check_target_distribution(df, target_column):\n",
|
| 85 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 86 |
+
"\n",
|
| 87 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 88 |
+
" plt.xlabel(target_column)\n",
|
| 89 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 90 |
+
" plt.grid(False)\n",
|
| 91 |
+
"\n",
|
| 92 |
+
" plt.show()\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 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 = df.drop(labels='Order_ID',axis=1)\n",
|
| 105 |
+
"df.head()"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 2: Write your code here:\n",
|
| 115 |
+
"def check_missing_values(df):\n",
|
| 116 |
+
" missing_values = df.isnull().sum()\n",
|
| 117 |
+
" print(\"Missing Values per Column:\")\n",
|
| 118 |
+
" print(missing_values[missing_values > 0])\n",
|
| 119 |
+
" if missing_values.any():\n",
|
| 120 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 121 |
+
" df.dropna(inplace=True)\n",
|
| 122 |
+
" print(\"\\nMissing Values handled.\")\n",
|
| 123 |
+
" print(\"\\nMissing Values per Column:\")\n",
|
| 124 |
+
" print(missing_values[missing_values > 0])\n",
|
| 125 |
+
"\n",
|
| 126 |
+
" else:\n",
|
| 127 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"check_missing_values(df)\n",
|
| 130 |
+
"\n"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 3: Write your code here:\n",
|
| 140 |
+
"def check_duplicates(df):\n",
|
| 141 |
+
" duplicates = df.duplicated().sum()\n",
|
| 142 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 143 |
+
" if duplicates > 0:\n",
|
| 144 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 145 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 146 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 147 |
+
" else:\n",
|
| 148 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"check_duplicates(df)"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"df.info()"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"df.head()"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"\n",
|
| 178 |
+
"# from sklearn.preprocessing import OneHotEncoder\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"# categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 181 |
+
"# for col in categorical_cols:\n",
|
| 182 |
+
"# print(f\"Encoding column: {col}\")\n",
|
| 183 |
+
"# ohe = OneHotEncoder(sparse_output=False)\n",
|
| 184 |
+
"# df[col] = ohe.fit_transform(df[[col]])\n",
|
| 185 |
+
"# df\n"
|
| 186 |
+
],
|
| 187 |
+
"execution_count": null,
|
| 188 |
+
"outputs": []
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"metadata": {},
|
| 193 |
+
"source": [
|
| 194 |
+
"# Task 4: Write your code here:\n",
|
| 195 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 196 |
+
"# Encode features and target using LabelEncoder\n",
|
| 197 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 198 |
+
"for col in categorical_cols:\n",
|
| 199 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 200 |
+
" le = LabelEncoder()\n",
|
| 201 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 202 |
+
"df"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 5: Write your code here:\n",
|
| 212 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"features = df.columns.drop(\"Delivery_Time\") # We DON'T SCALE THE TARGET\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"scaler = StandardScaler()\n",
|
| 217 |
+
"df[features] = scaler.fit_transform(df[features])\n",
|
| 218 |
+
"df.head()"
|
| 219 |
+
],
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"outputs": []
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"source": [
|
| 227 |
+
"# Task 6: Write your code here:"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"# Task 1: Write your code here:\n",
|
| 237 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 238 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 248 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 249 |
+
"from sklearn.model_selection import KFold\n",
|
| 250 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 251 |
+
"models = {\n",
|
| 252 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 253 |
+
"}\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"# Storage for results\n",
|
| 256 |
+
"all_results = {}\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"for name in models:\n",
|
| 259 |
+
" all_results[name] = {'mse': []}\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 263 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 266 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 269 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" for model_name, model in models.items():\n",
|
| 272 |
+
" print(f\"Training {model_name}...\")\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" # Train\n",
|
| 275 |
+
" model.fit(X_train, y_train)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # Predict\n",
|
| 278 |
+
" y_pred = model.predict(X_test)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Calculate metrics\n",
|
| 281 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" # Store results\n",
|
| 285 |
+
" all_results[model_name][\"mse\"].append(mse)\n",
|
| 286 |
+
"for model_name in all_results:\n",
|
| 287 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 288 |
+
" print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\\n\\n\")\n",
|
| 289 |
+
""
|
| 290 |
+
],
|
| 291 |
+
"execution_count": null,
|
| 292 |
+
"outputs": []
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"cell_type": "code",
|
| 296 |
+
"metadata": {},
|
| 297 |
+
"source": [
|
| 298 |
+
"# Calculate the baseline predictions (mean of the target)\n",
|
| 299 |
+
"baseline_pred = np.full_like(y, y.mean())\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Evaluate the baseline\n",
|
| 302 |
+
"baseline_mse = sklearn_mse(y, baseline_pred)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"print(f\"Baseline MSE (using mean target): {baseline_mse:.4f}\")\n"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# Task 1: Write your code here:\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"randf_model = models[\"Random Forest Regressor\"]\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# get feature importances and list in panda series\n",
|
| 319 |
+
"feature_importances = randf_model.feature_importances_\n",
|
| 320 |
+
"importance_df = pd.Series(feature_importances, index=X.columns)\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"# Sort in descending\n",
|
| 323 |
+
"importance_df = importance_df.sort_values(ascending=False)\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"# Create a bar plot\n",
|
| 326 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 327 |
+
"importance_df.plot(kind='bar')\n",
|
| 328 |
+
"plt.title('feature importances')\n",
|
| 329 |
+
"plt.xlabel('features')\n",
|
| 330 |
+
"plt.ylabel('importance')\n",
|
| 331 |
+
"plt.grid(False)\n",
|
| 332 |
+
"plt.tight_layout()\n",
|
| 333 |
+
"plt.show()"
|
| 334 |
+
],
|
| 335 |
+
"execution_count": null,
|
| 336 |
+
"outputs": []
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"cell_type": "code",
|
| 340 |
+
"metadata": {},
|
| 341 |
+
"source": [
|
| 342 |
+
"# Task 2: Write your code here:\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 345 |
+
"sns.histplot(y_pred, bins=30, kde=True, color='skyblue')\n",
|
| 346 |
+
"plt.title('predicted delivery time histogram')\n",
|
| 347 |
+
"plt.xlabel('predicted Delivery Time (minutes)')\n",
|
| 348 |
+
"plt.ylabel('frequency')\n",
|
| 349 |
+
"plt.grid(False)\n",
|
| 350 |
+
"plt.tight_layout()\n",
|
| 351 |
+
"plt.show()"
|
| 352 |
+
],
|
| 353 |
+
"execution_count": null,
|
| 354 |
+
"outputs": []
|
| 355 |
+
},
|
| 356 |
+
{
|
| 357 |
+
"cell_type": "code",
|
| 358 |
+
"metadata": {},
|
| 359 |
+
"source": [
|
| 360 |
+
"# Task Bonus: Write your code here:"
|
| 361 |
+
],
|
| 362 |
+
"execution_count": null,
|
| 363 |
+
"outputs": []
|
| 364 |
+
},
|
| 365 |
+
{
|
| 366 |
+
"cell_type": "code",
|
| 367 |
+
"metadata": {},
|
| 368 |
+
"source": [
|
| 369 |
+
"pip install catboost\n"
|
| 370 |
+
],
|
| 371 |
+
"execution_count": null,
|
| 372 |
+
"outputs": []
|
| 373 |
+
},
|
| 374 |
+
{
|
| 375 |
+
"cell_type": "code",
|
| 376 |
+
"metadata": {},
|
| 377 |
+
"source": [
|
| 378 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 379 |
+
"from catboost import CatBoostRegressor\n",
|
| 380 |
+
"from sklearn.model_selection import KFold\n",
|
| 381 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 382 |
+
"import numpy as np\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"# Initialize models for ensemble\n",
|
| 385 |
+
"model_rf = RandomForestRegressor(n_estimators=200, random_state=42)\n",
|
| 386 |
+
"model_catboost = CatBoostRegressor(random_state=42, verbose=0)\n",
|
| 387 |
+
"\n",
|
| 388 |
+
"# Storage for ensemble results\n",
|
| 389 |
+
"ensemble_mae_scores = []\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 392 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 393 |
+
"\n",
|
| 394 |
+
"print(\"Starting ensemble training ...!\")\n",
|
| 395 |
+
"\n",
|
| 396 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 397 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 398 |
+
"\n",
|
| 399 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 400 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 401 |
+
"\n",
|
| 402 |
+
" # Train RF\n",
|
| 403 |
+
" print(\"Training RandomForestRegressor...\")\n",
|
| 404 |
+
" model_rf.fit(X_train, y_train)\n",
|
| 405 |
+
" y_pred_rf = model_rf.predict(X_test)\n",
|
| 406 |
+
"\n",
|
| 407 |
+
" # Train CatBoost\n",
|
| 408 |
+
" print(\"Training CatBoostRegressor...\")\n",
|
| 409 |
+
" model_catboost.fit(X_train, y_train)\n",
|
| 410 |
+
" y_pred_catboost = model_catboost.predict(X_test)\n",
|
| 411 |
+
"\n",
|
| 412 |
+
" # Average predictions\n",
|
| 413 |
+
" y_pred_ensemble = (y_pred_rf + y_pred_catboost) / 2\n",
|
| 414 |
+
"\n",
|
| 415 |
+
" # Calculateing MAE for ensemble\n",
|
| 416 |
+
" mae_ensemble = mean_absolute_error(y_test, y_pred_ensemble)\n",
|
| 417 |
+
" ensemble_mae_scores.append(mae_ensemble)\n",
|
| 418 |
+
" print(f\"Ensemble MAE for Fold {fold_idx + 1}: {mae_ensemble:.4f}\")\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"# Print the averaged MAE across all folds for the ensemble\n",
|
| 421 |
+
"print(f\"\\nAverage Ensemble MAE across all folds: {np.mean(ensemble_mae_scores):.4f}\")\n"
|
| 422 |
+
],
|
| 423 |
+
"execution_count": null,
|
| 424 |
+
"outputs": []
|
| 425 |
+
}
|
| 426 |
+
],
|
| 427 |
+
"metadata": {
|
| 428 |
+
"kernelspec": {
|
| 429 |
+
"display_name": "Python 3",
|
| 430 |
+
"name": "python3"
|
| 431 |
+
},
|
| 432 |
+
"language_info": {
|
| 433 |
+
"name": "python"
|
| 434 |
+
}
|
| 435 |
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10 |
+
"from torch.utils.data import DataLoader\n",
|
| 11 |
+
"from torch.optim import Adam\n",
|
| 12 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 13 |
+
"import torch.nn.functional as F\n",
|
| 14 |
+
"import matplotlib.pyplot as plt\n",
|
| 15 |
+
"from torch.utils.data import DataLoader, TensorDataset\n"
|
| 16 |
+
],
|
| 17 |
+
"execution_count": null,
|
| 18 |
+
"outputs": []
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"cell_type": "code",
|
| 22 |
+
"metadata": {},
|
| 23 |
+
"source": [
|
| 24 |
+
"import kagglehub\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"# Download latest version\n",
|
| 27 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"print(\"Path to dataset files:\", path)"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"import os\n",
|
| 39 |
+
"import pandas as pd\n",
|
| 40 |
+
"import numpy as np\n",
|
| 41 |
+
"from PIL import Image\n",
|
| 42 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 43 |
+
"im\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"# Load Labels\n",
|
| 46 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 47 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"images = []\n",
|
| 50 |
+
"ages = []\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"# Load Images and Resize\n",
|
| 53 |
+
"print(\"Loading images...\")\n",
|
| 54 |
+
"for index, row in labels_df.iterrows():\n",
|
| 55 |
+
" img_name = row.iloc[0]\n",
|
| 56 |
+
" age = row.iloc[1]\n",
|
| 57 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
" if os.path.exists(img_path):\n",
|
| 60 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 61 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 62 |
+
" images.append(img_array)\n",
|
| 63 |
+
" ages.append(age)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"X = np.array(images)\n",
|
| 66 |
+
"y = np.array(ages)\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 69 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Split Data\n",
|
| 72 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 75 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 76 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 77 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\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 |
+
"\n"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# 2. Create TensorDataset objects\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 107 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"# 3. Create DataLoaders\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 |
+
"\n"
|
| 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 |
+
"\n",
|
| 131 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 132 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 135 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 136 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 137 |
+
],
|
| 138 |
+
"execution_count": null,
|
| 139 |
+
"outputs": []
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"cell_type": "code",
|
| 143 |
+
"metadata": {},
|
| 144 |
+
"source": [
|
| 145 |
+
"print(y_batch)"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# 5. Display sample images\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"# Get one batch of images and labels\n",
|
| 157 |
+
"images, labels = next(iter(train_loader))\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"# Display the first 6 images in the batch\n",
|
| 160 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"for i in range(6):\n",
|
| 163 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 164 |
+
" # we changed from (c, h, w) to (h, w, c) for matplotlib because it's colored\n",
|
| 165 |
+
" plt.imshow(images[i].permute(1, 2, 0))\n",
|
| 166 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 167 |
+
" plt.axis('off')\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"plt.tight_layout()\n",
|
| 170 |
+
"plt.show()"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# Task 1: Write your model class here:\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"class NN4Layer(nn.Module):\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 184 |
+
" super(NN4Layer, self).__init__()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 187 |
+
" self.layer1 = nn.Linear(input_dim, 128)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 190 |
+
" self.layer2 = nn.Linear(128, 64)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 193 |
+
" self.layer3 = nn.Linear(64, 32)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 196 |
+
" self.layer4 = nn.Linear(32, output_dim)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # ReLU activation for non-linearity\n",
|
| 199 |
+
" self.relu = nn.ReLU()\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" # Defines how input data flows through the network\n",
|
| 202 |
+
" def forward(self, x):\n",
|
| 203 |
+
" # First hidden layer\n",
|
| 204 |
+
" z1 = self.layer1(x)\n",
|
| 205 |
+
" a1 = self.relu(z1)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" # Second hidden layer\n",
|
| 208 |
+
" z2 = self.layer2(a1)\n",
|
| 209 |
+
" a2 = self.relu(z2)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # Second hidden layer\n",
|
| 212 |
+
" z3 = self.layer3(a2)\n",
|
| 213 |
+
" a3 = self.relu(z3)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Output layer (raw scores / logits)\n",
|
| 217 |
+
" output = self.layer4(a3) # there is something missing here, remember? :)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" return output\n"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 2: Write your training loop here:\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 231 |
+
" # Set the model to training mode\n",
|
| 232 |
+
" model.train()\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" running_loss = 0.0\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 237 |
+
" # Move batch to the selected device\n",
|
| 238 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 239 |
+
" y_batch = y_batch.to(device)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # Forward pass\n",
|
| 242 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 243 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" # Backward pass & optimization\n",
|
| 246 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 247 |
+
" loss.backward() # Compute gradients\n",
|
| 248 |
+
" optimizer.step() # Update model parameters\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" running_loss += loss.item()\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" # Average loss over all batches\n",
|
| 253 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" return avg_loss"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task 3: Write your validation loop here:\n",
|
| 265 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 266 |
+
" # Set the model to evaluation mode\n",
|
| 267 |
+
" model.eval()\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" running_loss = 0.0\n",
|
| 270 |
+
" correct = 0\n",
|
| 271 |
+
" total = 0\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" with torch.no_grad():\n",
|
| 274 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 275 |
+
" # Move data to device\n",
|
| 276 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 277 |
+
" y_batch = y_batch.to(device)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" # Forward pass\n",
|
| 280 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 281 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" running_loss += loss.item()\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" return avg_loss\n"
|
| 290 |
+
],
|
| 291 |
+
"execution_count": null,
|
| 292 |
+
"outputs": []
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"cell_type": "code",
|
| 296 |
+
"metadata": {},
|
| 297 |
+
"source": [
|
| 298 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# Device setup\n",
|
| 301 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"# Model parameters\n",
|
| 304 |
+
"input_dim = 3 * 36 * 36 # MNIST images flattened\n",
|
| 305 |
+
"hidden_dim = 14 # Design choice\n",
|
| 306 |
+
"output_dim = 1 # Digits 0–9\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Instantiate model\n",
|
| 309 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"# Print the model architecture\n",
|
| 312 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 313 |
+
"print(model)\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"# Calculate the total number of trainable parameters\n",
|
| 316 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 317 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"num_epochs = 20\n",
|
| 322 |
+
"learning_rate = 0.001\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"# Define criterion (loss function) - using MSE for regression\n",
|
| 325 |
+
"criterion = nn.MSELoss()\n",
|
| 326 |
+
"# Define optimizer\n",
|
| 327 |
+
"optimizer = Adam(model.parameters(), learning_rate)"
|
| 328 |
+
],
|
| 329 |
+
"execution_count": null,
|
| 330 |
+
"outputs": []
|
| 331 |
+
},
|
| 332 |
+
{
|
| 333 |
+
"cell_type": "code",
|
| 334 |
+
"metadata": {},
|
| 335 |
+
"source": [
|
| 336 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"# Run Training\n",
|
| 339 |
+
"train_losses = []\n",
|
| 340 |
+
"val_losses = []\n",
|
| 341 |
+
"val_accuracies = []\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"print('Starting Training...')\n",
|
| 344 |
+
"for epoch in range(num_epochs):\n",
|
| 345 |
+
" # Train one epoch\n",
|
| 346 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 347 |
+
"\n",
|
| 348 |
+
" # Validate\n",
|
| 349 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" train_losses.append(train_loss)\n",
|
| 352 |
+
" val_losses.append(val_loss)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"print('Training Complete!')"
|
| 357 |
+
],
|
| 358 |
+
"execution_count": null,
|
| 359 |
+
"outputs": []
|
| 360 |
+
},
|
| 361 |
+
{
|
| 362 |
+
"cell_type": "code",
|
| 363 |
+
"metadata": {},
|
| 364 |
+
"source": [
|
| 365 |
+
"# Task 1: Write your code here:\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"# Plotting results\n",
|
| 368 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 371 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 372 |
+
"plt.title('Loss over Epochs')\n",
|
| 373 |
+
"plt.xlabel('Epoch')\n",
|
| 374 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 375 |
+
"plt.legend()\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"plt.tight_layout()\n",
|
| 378 |
+
"plt.show()"
|
| 379 |
+
],
|
| 380 |
+
"execution_count": null,
|
| 381 |
+
"outputs": []
|
| 382 |
+
},
|
| 383 |
+
{
|
| 384 |
+
"cell_type": "code",
|
| 385 |
+
"metadata": {},
|
| 386 |
+
"source": [
|
| 387 |
+
"from sklearn.metrics import mean_squared_error\n",
|
| 388 |
+
"# Get predictions on test set\n",
|
| 389 |
+
"model.eval()\n",
|
| 390 |
+
"images, labels = next(iter(test_loader))\n",
|
| 391 |
+
"# Move images to device\n",
|
| 392 |
+
"images = images.to(device)\n",
|
| 393 |
+
"labels = labels.to(device)\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"with torch.no_grad():\n",
|
| 396 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 397 |
+
" predictions = outputs.cpu().numpy()\n",
|
| 398 |
+
"\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"mse = mean_squared_error(labels.numpy(), predictions) # not the entire data, just an intuation to show that baseline is high\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"\n",
|
| 403 |
+
"print(\"Model Evaluation\")\n",
|
| 404 |
+
"print(f\" MSE: {mse:.2f}\")\n"
|
| 405 |
+
],
|
| 406 |
+
"execution_count": null,
|
| 407 |
+
"outputs": []
|
| 408 |
+
},
|
| 409 |
+
{
|
| 410 |
+
"cell_type": "code",
|
| 411 |
+
"metadata": {},
|
| 412 |
+
"source": [
|
| 413 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 414 |
+
"\n",
|
| 415 |
+
"# Set model to evaluation mode\n",
|
| 416 |
+
"model.eval()\n",
|
| 417 |
+
"# Get one batch from the test DataLoader\n",
|
| 418 |
+
"images, labels = next(iter(test_loader))\n",
|
| 419 |
+
"# Move images to device\n",
|
| 420 |
+
"images = images.to(device)\n",
|
| 421 |
+
"labels = labels.to(device)\n",
|
| 422 |
+
"\n",
|
| 423 |
+
"with torch.no_grad():\n",
|
| 424 |
+
" # Flatten images before passing to the model\n",
|
| 425 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 426 |
+
" predictions = outputs\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"# Move tensors back to CPU for plotting\n",
|
| 429 |
+
"images = images.cpu()\n",
|
| 430 |
+
"labels = labels.cpu()\n",
|
| 431 |
+
"predictions = predictions.cpu()\n",
|
| 432 |
+
"\n",
|
| 433 |
+
"# Plot first 6 predictions\n",
|
| 434 |
+
"plt.figure(figsize=(12, 4))\n",
|
| 435 |
+
"for i in range(6):\n",
|
| 436 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 437 |
+
" plt.imshow(images[i].permute(1, 2, 0), cmap='gray')\n",
|
| 438 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 439 |
+
" plt.axis('off')\n",
|
| 440 |
+
"\n",
|
| 441 |
+
"plt.tight_layout()\n",
|
| 442 |
+
"plt.show()"
|
| 443 |
+
],
|
| 444 |
+
"execution_count": null,
|
| 445 |
+
"outputs": []
|
| 446 |
+
},
|
| 447 |
+
{
|
| 448 |
+
"cell_type": "code",
|
| 449 |
+
"metadata": {},
|
| 450 |
+
"source": [],
|
| 451 |
+
"execution_count": null,
|
| 452 |
+
"outputs": []
|
| 453 |
+
}
|
| 454 |
+
],
|
| 455 |
+
"metadata": {
|
| 456 |
+
"kernelspec": {
|
| 457 |
+
"display_name": "Python 3",
|
| 458 |
+
"name": "python3"
|
| 459 |
+
},
|
| 460 |
+
"language_info": {
|
| 461 |
+
"name": "python"
|
| 462 |
+
}
|
| 463 |
+
},
|
| 464 |
+
"nbformat": 4,
|
| 465 |
+
"nbformat_minor": 0
|
| 466 |
+
}
|
submissions_extracted/706/Q3.ipynb
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 os\n",
|
| 12 |
+
"from tqdm import tqdm\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"%matplotlib inline"
|
| 15 |
+
],
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"outputs": []
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"import kagglehub\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Download latest version\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"print(\"Path to dataset files:\", path)"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 1: Write your code here:\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"df = pd.read_csv(csv_path)"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 2: Write your code here:\n",
|
| 56 |
+
"df.head()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 3: Write your code here:\n",
|
| 66 |
+
"df.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:\n",
|
| 76 |
+
"df.describe()"
|
| 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 |
+
"def check_missing_values(df):\n",
|
| 88 |
+
" missing_values = df.isnull().sum()\n",
|
| 89 |
+
" print(\"Missing Values per Column:\")\n",
|
| 90 |
+
" print(missing_values[missing_values > 0])\n",
|
| 91 |
+
" if missing_values.any():\n",
|
| 92 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 93 |
+
" df.fillna(0,inplace=True)\n",
|
| 94 |
+
" #it's fillid with zeros, I know it's bad but this is the best available solution NOW, mean will take time!!!\n",
|
| 95 |
+
"\n",
|
| 96 |
+
" else:\n",
|
| 97 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"check_missing_values(df)\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 2: Write your code here:\n",
|
| 109 |
+
"def check_duplicates(df):\n",
|
| 110 |
+
" duplicates = df.duplicated().sum()\n",
|
| 111 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 112 |
+
" if duplicates > 0:\n",
|
| 113 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 114 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 115 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 116 |
+
" else:\n",
|
| 117 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"check_duplicates(df)"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# Task 3: Write your code here:\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"# no need for encoding!"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 4: Write your code here:\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"scaler = StandardScaler()\n",
|
| 146 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 147 |
+
"df.head()\n"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 5: Write your code here:\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"# 1. Is the target imbalanced?\n",
|
| 159 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 160 |
+
" print(\"Target Distribution:\")\n",
|
| 161 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 162 |
+
" sns.countplot(x=df[target_column])\n",
|
| 163 |
+
" plt.title(\"Target Distribution\")\n",
|
| 164 |
+
" plt.show()\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"check_target_imbalance(df, \"Target\")\n",
|
| 167 |
+
"\n"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 1: Write your code here:\n",
|
| 177 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 178 |
+
"y = df['Target'].astype(float)"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"pip install catboost\n"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 197 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
|
| 198 |
+
],
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"outputs": []
|
| 201 |
+
},
|
| 202 |
+
{
|
| 203 |
+
"cell_type": "code",
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"source": [
|
| 206 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"from catboost import CatBoostClassifier\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"sklearn_models = {\n",
|
| 211 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 212 |
+
" verbose=0,\n",
|
| 213 |
+
" n_estimators=320,\n",
|
| 214 |
+
" max_depth=4\n",
|
| 215 |
+
" )\n",
|
| 216 |
+
"}\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"all_results = {}\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"for name in sklearn_models:\n",
|
| 222 |
+
" all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"n_splits = 5 # K\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 229 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 234 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" # 1. Split data\n",
|
| 237 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 238 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # 2. Train & Validate sklearn models\n",
|
| 241 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 242 |
+
" print(f\"Training {model_name}...\")\n",
|
| 243 |
+
" model.fit(X_train, y_train) # train\n",
|
| 244 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 247 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 248 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 249 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 250 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 253 |
+
" all_results[model_name]['precision'].append(precision)\n",
|
| 254 |
+
" all_results[model_name]['recall'].append(recall)\n",
|
| 255 |
+
" all_results[model_name]['f1'].append(f1)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"for model_name in all_results:\n",
|
| 260 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 261 |
+
" print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n",
|
| 262 |
+
" print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n",
|
| 263 |
+
" print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n",
|
| 264 |
+
" print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"cell_type": "code",
|
| 271 |
+
"metadata": {},
|
| 272 |
+
"source": [
|
| 273 |
+
"# Calculate the majority class baseline\n",
|
| 274 |
+
"majority_class = y.value_counts().idxmax()\n",
|
| 275 |
+
"baseline_pred = [majority_class] * len(y)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"# Evaluate the baseline\n",
|
| 278 |
+
"baseline_accuracy = accuracy_score(y, baseline_pred)\n",
|
| 279 |
+
"baseline_precision = precision_score(y, baseline_pred, average='weighted', zero_division=0)\n",
|
| 280 |
+
"baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_division=0)\n",
|
| 281 |
+
"baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n",
|
| 284 |
+
"print(f\"Baseline Precision: {baseline_precision:.4f}\")\n",
|
| 285 |
+
"print(f\"Baseline Recall: {baseline_recall:.4f}\")\n",
|
| 286 |
+
"print(f\"Baseline F1-Score: {baseline_f1:.4f}\")\n"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
"# Task 1: Write your code here:\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"randf_model = sklearn_models[\"CatBoost\"]\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"# get feature importances and list in panda series\n",
|
| 300 |
+
"feature_importances = randf_model.feature_importances_\n",
|
| 301 |
+
"importance_df = pd.Series(feature_importances, index=X.columns)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"# Sort in descending\n",
|
| 304 |
+
"importance_df = importance_df.sort_values(ascending=False)\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"# Create a bar plot\n",
|
| 307 |
+
"plt.figure(figsize=(40, 6))\n",
|
| 308 |
+
"importance_df.plot(kind='bar')\n",
|
| 309 |
+
"plt.title('feature importances')\n",
|
| 310 |
+
"plt.xlabel('features')\n",
|
| 311 |
+
"plt.ylabel('importance')\n",
|
| 312 |
+
"plt.grid(False)\n",
|
| 313 |
+
"plt.tight_layout()\n",
|
| 314 |
+
"plt.show()"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Task 2: Write your code here:\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"print('The Golden Feature IS: ' , importance_df[0])"
|
| 326 |
+
],
|
| 327 |
+
"execution_count": null,
|
| 328 |
+
"outputs": []
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"cell_type": "code",
|
| 332 |
+
"metadata": {},
|
| 333 |
+
"source": [
|
| 334 |
+
"# Task Bonus: Write your code here:"
|
| 335 |
+
],
|
| 336 |
+
"execution_count": null,
|
| 337 |
+
"outputs": []
|
| 338 |
+
}
|
| 339 |
+
],
|
| 340 |
+
"metadata": {
|
| 341 |
+
"kernelspec": {
|
| 342 |
+
"display_name": "Python 3",
|
| 343 |
+
"name": "python3"
|
| 344 |
+
},
|
| 345 |
+
"language_info": {
|
| 346 |
+
"name": "python"
|
| 347 |
+
}
|
| 348 |
+
},
|
| 349 |
+
"nbformat": 4,
|
| 350 |
+
"nbformat_minor": 0
|
| 351 |
+
}
|
submissions_extracted/707/Q1.ipynb
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import numpy as np\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import matplotlib.pyplot as plt\n",
|
| 24 |
+
"import os\n",
|
| 25 |
+
"import kagglehub\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 28 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 29 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 30 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"import warnings\n",
|
| 33 |
+
"warnings.filterwarnings('ignore')\n",
|
| 34 |
+
"\n"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# Task 1: Write your code here:\n",
|
| 44 |
+
"# Load the dataset\n",
|
| 45 |
+
"df_path=os.path.join(path, 'Q1_data.csv')\n",
|
| 46 |
+
"df = pd.read_csv(df_path)\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"print(f\"Dataset shape: {df.shape}\")\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 2: Write your code here:\n",
|
| 58 |
+
"df.head()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 3: Write your code here:\n",
|
| 68 |
+
"df.info()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 4: Write your code here:\n",
|
| 78 |
+
"df.describe()"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 5: Write your code here:\n",
|
| 88 |
+
"################### ارجع\n",
|
| 89 |
+
"y= df[\"Delivery_Time\"].value_counts()\n",
|
| 90 |
+
"distance=df[\"Distance_km\"].value_counts()\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"plt.scatter(y.index,y)"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# Task 1: Write your code here:\n",
|
| 110 |
+
"df.drop(columns=\"Order_ID\")"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"df.info()\n"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"\n",
|
| 129 |
+
"missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
|
| 130 |
+
"missing_data = pd.DataFrame({\n",
|
| 131 |
+
" 'Column': missing_percentage.index,\n",
|
| 132 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 133 |
+
"})\n",
|
| 134 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 137 |
+
"missing_data.head(200)"
|
| 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 |
+
"#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"df.dropna(subset=['Delivery_Time','Weather','Traffic_Level',\"Time_of_Day\",\"Courier_Experience_yrs\"])\n"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"\n",
|
| 159 |
+
"\n"
|
| 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 |
+
"#Check and remove duplicates if any exist\n",
|
| 170 |
+
"def check_duplicates(df):\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" #TODO: get duplicated data using pandas\n",
|
| 173 |
+
" duplicates = df.duplicated().sum()\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 176 |
+
" if duplicates > 0:\n",
|
| 177 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 178 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 179 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 180 |
+
" else:\n",
|
| 181 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"check_duplicates(df)"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 4: Write your code here:\n",
|
| 193 |
+
"#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
|
| 194 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 195 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 198 |
+
"df['Delivery_Time'] = df['Delivery_Time'].fillna(0)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 201 |
+
"le = LabelEncoder()\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"# Encode the target column\n",
|
| 204 |
+
"df[\"Weather\"] = le.fit_transform(df[\"Weather\"])\n",
|
| 205 |
+
"df[\"Traffic_Level\"] = le.fit_transform(df[\"Traffic_Level\"])\n",
|
| 206 |
+
"df[\"Time_of_Day\"] = le.fit_transform(df[\"Time_of_Day\"])\n",
|
| 207 |
+
"df[\"Vehicle_Type\"] = le.fit_transform(df[\"Vehicle_Type\"])\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"df"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"cell_type": "code",
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"source": [
|
| 218 |
+
"# Task 5: Write your code here:\n",
|
| 219 |
+
"#Apply feature scaling for all features (Use StandardScaler)\n",
|
| 220 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 224 |
+
"data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 227 |
+
],
|
| 228 |
+
"execution_count": null,
|
| 229 |
+
"outputs": []
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"metadata": {},
|
| 234 |
+
"source": [
|
| 235 |
+
"# Task 6: Write your code here:\n",
|
| 236 |
+
"#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 237 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 238 |
+
" print(\"Target Distribution:\")\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 241 |
+
" plt.show()\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"check_target_imbalance(df, \"Delivery_Time\")"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"# Task 1: Write your code here:\n",
|
| 253 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 254 |
+
"y = df[\"Delivery_Time\"].astype(float)\n",
|
| 255 |
+
"df['Delivery_Time'] = df['Delivery_Time'].fillna('none')\n",
|
| 256 |
+
"y.describe()"
|
| 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 |
+
"#Use the correct split: KFold OR StratifiedKFold\n",
|
| 267 |
+
"#Train a RandomForest model\n",
|
| 268 |
+
"#Evaluate using MAE (Mean Absolute Error) ONLY\n",
|
| 269 |
+
"#Print the averaged score across all folds\n",
|
| 270 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 271 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 272 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"\"\"\"\"Random Forest\": RandomForestClassifier(\n",
|
| 275 |
+
" n_estimators=320, # Number of trees\n",
|
| 276 |
+
" max_depth=4\"\"\"\n",
|
| 277 |
+
"MEA=[]\n",
|
| 278 |
+
"n_splits = 5 # K\n",
|
| 279 |
+
"model = RandomForestClassifier(\n",
|
| 280 |
+
" n_estimators=320, # Number of trees\n",
|
| 281 |
+
" max_depth=4)\n",
|
| 282 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 283 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 286 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" # 1. Split data\n",
|
| 289 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 290 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 291 |
+
" model.fit(X_train, y_train) # train\n",
|
| 292 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 293 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 294 |
+
" MEA.append(mae)\n",
|
| 295 |
+
"avg_MEA=0\n",
|
| 296 |
+
"for i in MEA:\n",
|
| 297 |
+
" avg_MEA+=i\n",
|
| 298 |
+
"print(\"the averaged score across all folds is :\",avg_MEA/n_splits)"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"df.info()"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "code",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"# Task 1: Write your code here:\n",
|
| 317 |
+
"feature_cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level',\"Time_of_Day\",\"Vehicle_Type\",\"Preparation_Time_min\",\"Courier_Experience_yrs\"]\n",
|
| 318 |
+
"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(importance['feature'], importance['importance'], color='purple')\n",
|
| 325 |
+
"plt.xlabel('Importance')\n",
|
| 326 |
+
"plt.title('Feature Importance')\n",
|
| 327 |
+
"plt.gca().invert_yaxis()\n",
|
| 328 |
+
"plt.show()\n",
|
| 329 |
+
"\n"
|
| 330 |
+
],
|
| 331 |
+
"execution_count": null,
|
| 332 |
+
"outputs": []
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"cell_type": "code",
|
| 336 |
+
"metadata": {},
|
| 337 |
+
"source": [
|
| 338 |
+
"# Task 2: Write your code here:\n",
|
| 339 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 340 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 341 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 342 |
+
"plt.xlabel('Delivery Time')\n",
|
| 343 |
+
"plt.ylabel('Frequency')\n",
|
| 344 |
+
"plt.show()\n",
|
| 345 |
+
"#note the 0 mean nan"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
},
|
| 350 |
+
{
|
| 351 |
+
"cell_type": "code",
|
| 352 |
+
"metadata": {},
|
| 353 |
+
"source": [
|
| 354 |
+
"# Task Bonus: Write your code here:"
|
| 355 |
+
],
|
| 356 |
+
"execution_count": null,
|
| 357 |
+
"outputs": []
|
| 358 |
+
}
|
| 359 |
+
],
|
| 360 |
+
"metadata": {
|
| 361 |
+
"kernelspec": {
|
| 362 |
+
"display_name": "Python 3",
|
| 363 |
+
"name": "python3"
|
| 364 |
+
},
|
| 365 |
+
"language_info": {
|
| 366 |
+
"name": "python"
|
| 367 |
+
}
|
| 368 |
+
},
|
| 369 |
+
"nbformat": 4,
|
| 370 |
+
"nbformat_minor": 0
|
| 371 |
+
}
|
submissions_extracted/707/Q2.ipynb
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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}\")\n"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [],
|
| 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 |
+
"import kagglehub\n",
|
| 85 |
+
"import pandas as pd\n",
|
| 86 |
+
"import torch\n",
|
| 87 |
+
"import torch.nn as nn\n",
|
| 88 |
+
"from torch.optim import AdamW\n",
|
| 89 |
+
"import matplotlib.pyplot as plt\n",
|
| 90 |
+
"import torch.nn.functional as F\n",
|
| 91 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 92 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 93 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"X_train = torch.tensor(X_train, dtype=torch.int32)\n",
|
| 96 |
+
"X_test = torch.tensor(X_test, dtype=torch.int32)\n",
|
| 97 |
+
"y_train = torch.tensor(y_train, dtype=torch.int32)\n",
|
| 98 |
+
"y_test = torch.tensor(y_test, dtype=torch.int32)\n",
|
| 99 |
+
"X_train.dtype"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# 2. Create TensorDataset objects\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 111 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# 3. Create DataLoaders\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"from torch.utils.data import DataLoader\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"# DataLoader for training data\n",
|
| 125 |
+
"train_loader = DataLoader(\n",
|
| 126 |
+
" train_dataset,\n",
|
| 127 |
+
" batch_size=32,\n",
|
| 128 |
+
" shuffle=True,\n",
|
| 129 |
+
" num_workers=2\n",
|
| 130 |
+
")\n",
|
| 131 |
+
"# DataLoader for test/validation data\n",
|
| 132 |
+
"test_loader = DataLoader(\n",
|
| 133 |
+
" test_dataset,\n",
|
| 134 |
+
" batch_size=32,\n",
|
| 135 |
+
" shuffle=False,\n",
|
| 136 |
+
" num_workers=2\n",
|
| 137 |
+
")\n",
|
| 138 |
+
"# Get the first batch from the training DataLoader\n",
|
| 139 |
+
"\n"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# 4. Print shape of one batch\n",
|
| 149 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 150 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 151 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 152 |
+
"\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Get one batch of images and labels\n",
|
| 162 |
+
"images, labels = next(iter(train_loader))\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"# Display the first 6 images in the batch\n",
|
| 165 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"for i in range(6):\n",
|
| 168 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" plt.imshow(img)\n",
|
| 173 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 174 |
+
" plt.axis('off')\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"plt.tight_layout()\n",
|
| 177 |
+
"plt.show()"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 1: Write your model class here:\n",
|
| 187 |
+
"class NN3Layer(nn.Module):\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 190 |
+
" super(NN3Layer, self).__init__()\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 193 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 196 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 199 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 200 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # ReLU activation for non-linearity\n",
|
| 203 |
+
" self.relu = nn.ReLU()\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" # Defines how input data flows through the network\n",
|
| 206 |
+
" def forward(self, x):\n",
|
| 207 |
+
" # First hidden layer\n",
|
| 208 |
+
" z1 = self.layer1(x)\n",
|
| 209 |
+
" a1 = self.relu(z1)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # Second hidden layer\n",
|
| 212 |
+
" z2 = self.layer2(a1)\n",
|
| 213 |
+
" a2 = self.relu(z2)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # Output layer (raw scores / logits)\n",
|
| 216 |
+
" z3 = self.layer2(a2)\n",
|
| 217 |
+
" a3 = self.relu(z3)\n",
|
| 218 |
+
" output = self.layer3(a3)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" return output\n"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 230 |
+
" # Set the model to training mode\n",
|
| 231 |
+
" model.train()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" running_loss = 0\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 236 |
+
" # Move batch to the selected device\n",
|
| 237 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 238 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Forward pass (continuous output)\n",
|
| 241 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 242 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" # Backward pass & optimization\n",
|
| 245 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 246 |
+
" loss.backward() # Compute gradients\n",
|
| 247 |
+
" optimizer.step() # Update model parameters\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" running_loss += loss.item()\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" # Average loss over all batches\n",
|
| 252 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" return avg_loss"
|
| 255 |
+
],
|
| 256 |
+
"execution_count": null,
|
| 257 |
+
"outputs": []
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"metadata": {},
|
| 262 |
+
"source": [
|
| 263 |
+
"# Task 3: Write your validation loop here:\n",
|
| 264 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 265 |
+
" # Set the model to evaluation mode\n",
|
| 266 |
+
" model.eval()\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" running_loss = 0.0\n",
|
| 269 |
+
" correct = 0\n",
|
| 270 |
+
" total = 0\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" with torch.no_grad():\n",
|
| 273 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 274 |
+
" # Move data to device\n",
|
| 275 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 276 |
+
" y_batch = y_batch.to(device)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" # Forward pass\n",
|
| 279 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 280 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 281 |
+
" running_loss += loss.item()\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" # Apply Softmax to get probabilities\n",
|
| 284 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" # Multiclass predictions\n",
|
| 287 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" # Accuracy calculation\n",
|
| 290 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 291 |
+
" total += y_batch.size(0)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 294 |
+
" accuracy = correct / total\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" return avg_loss, accuracy\n"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 306 |
+
"# Device setup\n",
|
| 307 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 308 |
+
"\n",
|
| 309 |
+
"# Model parameters\n",
|
| 310 |
+
"input_dim = 2000 # number of images\n",
|
| 311 |
+
"hidden_dim = 20\n",
|
| 312 |
+
"output_dim = 1 # one age\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# Instantiate model\n",
|
| 315 |
+
"model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"# Print the model architecture\n",
|
| 318 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 319 |
+
"print(model)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"# Calculate the total number of trainable parameters\n",
|
| 322 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 323 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 324 |
+
],
|
| 325 |
+
"execution_count": null,
|
| 326 |
+
"outputs": []
|
| 327 |
+
},
|
| 328 |
+
{
|
| 329 |
+
"cell_type": "code",
|
| 330 |
+
"metadata": {},
|
| 331 |
+
"source": [
|
| 332 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 333 |
+
"num_epochs = 20\n",
|
| 334 |
+
"learning_rate = 0.001\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 337 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 338 |
+
"# Define optimizer\n",
|
| 339 |
+
"optimizer = Adam(model.parameters(), learning_rate)\n",
|
| 340 |
+
"# Run Training\n",
|
| 341 |
+
"train_losses = []\n",
|
| 342 |
+
"val_losses = []\n",
|
| 343 |
+
"val_accuracies = []\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"print('Starting Training...')\n",
|
| 346 |
+
"for epoch in range(num_epochs):\n",
|
| 347 |
+
" # Train one epoch\n",
|
| 348 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 349 |
+
"\n",
|
| 350 |
+
" # Validate\n",
|
| 351 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" train_losses.append(train_loss)\n",
|
| 354 |
+
" val_losses.append(val_loss)\n",
|
| 355 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"print('Training Complete!')"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"source": [
|
| 368 |
+
"# Task 1: Write your code here:\n",
|
| 369 |
+
"# Plotting results\n",
|
| 370 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 373 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 374 |
+
"plt.title('Loss over Epochs')\n",
|
| 375 |
+
"plt.xlabel('Epoch')\n",
|
| 376 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 377 |
+
"plt.legend()\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"plt.tight_layout()\n",
|
| 380 |
+
"plt.show()"
|
| 381 |
+
],
|
| 382 |
+
"execution_count": null,
|
| 383 |
+
"outputs": []
|
| 384 |
+
},
|
| 385 |
+
{
|
| 386 |
+
"cell_type": "code",
|
| 387 |
+
"metadata": {},
|
| 388 |
+
"source": [
|
| 389 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 390 |
+
],
|
| 391 |
+
"execution_count": null,
|
| 392 |
+
"outputs": []
|
| 393 |
+
}
|
| 394 |
+
],
|
| 395 |
+
"metadata": {
|
| 396 |
+
"kernelspec": {
|
| 397 |
+
"display_name": "Python 3",
|
| 398 |
+
"name": "python3"
|
| 399 |
+
},
|
| 400 |
+
"language_info": {
|
| 401 |
+
"name": "python"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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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: Read the dataset Q3_data.csv using read_csv()\n",
|
| 27 |
+
"import numpy as np\n",
|
| 28 |
+
"import pandas as pd\n",
|
| 29 |
+
"import matplotlib.pyplot as plt\n",
|
| 30 |
+
"import os\n",
|
| 31 |
+
"import kagglehub\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 34 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 35 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 36 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"import warnings\n",
|
| 39 |
+
"warnings.filterwarnings('ignore')\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"df_path=os.path.join(path, 'Q3_data.csv')\n",
|
| 43 |
+
"df = pd.read_csv(df_path)\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"print(f\"Dataset shape: {df.shape}\")"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 2: Write your code here: Inspect the first few rows using head()\n",
|
| 55 |
+
"df.head(1)"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 3: Write your code here:Display dataset information using info()\n",
|
| 65 |
+
"df.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: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: Handle missing values appropriately\n",
|
| 85 |
+
"\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 |
+
"print(list(missing_data[\"Column\"].unique()))\n"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"dropnaall=list(missing_data[\"Column\"].unique())\n",
|
| 104 |
+
"for i in dropnaall:\n",
|
| 105 |
+
" print(i)\n",
|
| 106 |
+
" df.dropna(subset=[i])\n",
|
| 107 |
+
"\n"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 2: Write your code here: Check and remove duplicates if any exis\n",
|
| 124 |
+
"def check_duplicates(df):\n",
|
| 125 |
+
"\n",
|
| 126 |
+
" #TODO: get duplicated data using pandas\n",
|
| 127 |
+
" duplicates = df.duplicated().sum()\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 130 |
+
" if duplicates > 0:\n",
|
| 131 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 132 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 133 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 134 |
+
" else:\n",
|
| 135 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"check_duplicates(df)"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# Task 3: Write your code here: Encode categorical variables if needed\n",
|
| 147 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 150 |
+
"# we don't need"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 4: Write your code here: Apply feature scaling to numerical features (Use StandardScaler)\n",
|
| 160 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 164 |
+
"data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 5: Write your code here: Check for target imbalance and state if it is imbalanced or not\n",
|
| 176 |
+
"def check_target_imbalance(df,target_column):\n",
|
| 177 |
+
" print(\"Target Distribution:\")\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 180 |
+
" plt.show()\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"check_target_imbalance(df, \"Target\")"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Task 1: Write your code here:Split the dataset into features (X) and target (y)\n",
|
| 192 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 193 |
+
"y = df[\"Target\"].astype(float)\n",
|
| 194 |
+
"y.describe()"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"!pip install catboost\n"
|
| 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 |
+
"\"\"\"2. Use the correct split: **KFold** OR **StratifiedKFold**\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"3. Train a **CatBoostClassifier** model\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"4. Evaluate using the appropriate metric only (Accuracy vs. F1 Score).\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"5. Print the averaged score across all folds\"\"\"\n",
|
| 220 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 221 |
+
"#Use the correct split: KFold OR StratifiedKFold\n",
|
| 222 |
+
"#Train a RandomForest model\n",
|
| 223 |
+
"#Evaluate using MAE (Mean Absolute Error) ONLY\n",
|
| 224 |
+
"#Print the averaged score across all folds\n",
|
| 225 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 228 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 229 |
+
"# Import models\n",
|
| 230 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 231 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 232 |
+
"from sklearn.svm import SVC\n",
|
| 233 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 234 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 235 |
+
"from xgboost import XGBClassifier\n",
|
| 236 |
+
"from catboost import CatBoostClassifier\n",
|
| 237 |
+
"Accuracy=[]\n",
|
| 238 |
+
"f1_scoree=[]\n",
|
| 239 |
+
"n_splits = 5 # K\n",
|
| 240 |
+
"model = CatBoostClassifier(\n",
|
| 241 |
+
" verbose=0,\n",
|
| 242 |
+
" n_estimators=320,\n",
|
| 243 |
+
" max_depth=4)\n",
|
| 244 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 245 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 248 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # 1. Split data\n",
|
| 251 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 252 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 253 |
+
" model.fit(X_train, y_train) # train\n",
|
| 254 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 255 |
+
" ac=accuracy_score(y_test, y_pred)\n",
|
| 256 |
+
" f1=f1_score(y_test, y_pred,average='macro')\n",
|
| 257 |
+
" Accuracy.append(ac)\n",
|
| 258 |
+
" f1_scoree.append(f1)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"avg_f1=0\n",
|
| 261 |
+
"avg_ac=0\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"for i in Accuracy:\n",
|
| 264 |
+
" avg_ac+=i\n",
|
| 265 |
+
"for i in f1_scoree:\n",
|
| 266 |
+
" avg_ac+=i\n",
|
| 267 |
+
"print(\"the averaged score across all folds is Accuracy:\",avg_ac/n_splits)\n",
|
| 268 |
+
"print(\"the averaged score across all folds is avg_f1:\",avg_f1/n_splits)\n",
|
| 269 |
+
"\n"
|
| 270 |
+
],
|
| 271 |
+
"execution_count": null,
|
| 272 |
+
"outputs": []
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"cell_type": "code",
|
| 276 |
+
"metadata": {},
|
| 277 |
+
"source": [
|
| 278 |
+
"# Task 1: Write your code here:\n",
|
| 279 |
+
"# Task 1: Write your code here:\n",
|
| 280 |
+
"feature_cols = df.columns()\n",
|
| 281 |
+
"importance = pd.DataFrame({\n",
|
| 282 |
+
" 'feature': feature_cols,\n",
|
| 283 |
+
" 'importance': model.feature_importances_\n",
|
| 284 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 287 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 288 |
+
"plt.xlabel('Importance')\n",
|
| 289 |
+
"plt.title('Feature Importance')\n",
|
| 290 |
+
"plt.gca().invert_yaxis()\n",
|
| 291 |
+
"plt.show()\n",
|
| 292 |
+
"\n"
|
| 293 |
+
],
|
| 294 |
+
"execution_count": null,
|
| 295 |
+
"outputs": []
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"cell_type": "code",
|
| 299 |
+
"metadata": {},
|
| 300 |
+
"source": [
|
| 301 |
+
"# Task 2: Write your code here:\n",
|
| 302 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 303 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 304 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 305 |
+
"plt.xlabel('Delivery Time')\n",
|
| 306 |
+
"plt.ylabel('Frequency')\n",
|
| 307 |
+
"plt.show()"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "code",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"# Task Bonus: Write your code here:"
|
| 317 |
+
],
|
| 318 |
+
"execution_count": null,
|
| 319 |
+
"outputs": []
|
| 320 |
+
}
|
| 321 |
+
],
|
| 322 |
+
"metadata": {
|
| 323 |
+
"kernelspec": {
|
| 324 |
+
"display_name": "Python 3",
|
| 325 |
+
"name": "python3"
|
| 326 |
+
},
|
| 327 |
+
"language_info": {
|
| 328 |
+
"name": "python"
|
| 329 |
+
}
|
| 330 |
+
},
|
| 331 |
+
"nbformat": 4,
|
| 332 |
+
"nbformat_minor": 0
|
| 333 |
+
}
|
submissions_extracted/708/Q1.ipynb
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"# We need to import the needed libraries\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"import pandas as pd\n",
|
| 25 |
+
"import os\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load the CSV file\n",
|
| 28 |
+
"df_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 29 |
+
"df = pd.read_csv(df_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 |
+
"#Look at the data and analyze\n",
|
| 40 |
+
"print(f\"Shape: {df.shape}\")\n",
|
| 41 |
+
"df.head()\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"#Order ID in not important, I should drop\n",
|
| 44 |
+
"#Delivery time is the target\n",
|
| 45 |
+
"#4 object columns, Labelencoder should be used"
|
| 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 |
+
"#9 total columns, 8 are needed: 7 for X, delivery time for y, Order id will be dropped\n",
|
| 56 |
+
"df.info()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 4: Write your code here:\n",
|
| 66 |
+
"#Not much extra info to gather\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 |
+
"#Importing plt\n",
|
| 78 |
+
"import matplotlib.pyplot as plt\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"# Target distribution\n",
|
| 81 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 82 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 83 |
+
"plt.title('Time Distribution')\n",
|
| 84 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 85 |
+
"plt.ylabel('Frequency')\n",
|
| 86 |
+
"plt.show()"
|
| 87 |
+
],
|
| 88 |
+
"execution_count": null,
|
| 89 |
+
"outputs": []
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "code",
|
| 93 |
+
"metadata": {},
|
| 94 |
+
"source": [
|
| 95 |
+
"# Task 1: Write your code here:\n",
|
| 96 |
+
"df_clean = df.drop(\"Order_ID\", axis= 1).copy()"
|
| 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 |
+
"#Lets drop missing value in the target column since without those we cant check our prediction.\n",
|
| 107 |
+
"#106 Rows will be dropped after this operation\n",
|
| 108 |
+
"df_clean = df_clean.dropna(subset= 'Delivery_Time').copy()\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"#3 rows should be fillna with None but the courier experience yrs should filled with the average of yrs\n",
|
| 111 |
+
"df_clean['Weather'] = df_clean['Weather'].fillna(\"None\")\n",
|
| 112 |
+
"df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(\"None\")\n",
|
| 113 |
+
"df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(\"None\")\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].dropna().mean())\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"# 'Traffic_Level', 'Vehicle_Type'\n",
|
| 118 |
+
"#Checking missing values Note: This is the first thing I wrote, I kept the code at the end of the block so that after cleaning I can check the changes.\n",
|
| 119 |
+
"print(\"Missing values:\")\n",
|
| 120 |
+
"print(df_clean.isnull().sum())\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"#Check shape after cleaning NaN\n",
|
| 123 |
+
"print(f\"Shape after cleaning NaN: {df_clean.shape}\")"
|
| 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 |
+
"df_clean = df_clean.drop_duplicates().copy()\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"#Check shape after clean\n",
|
| 136 |
+
"print(f\"Shape after dropping duplicates: {df_clean.shape}\")"
|
| 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 |
+
"#Import OHE and standard scaler as well\n",
|
| 147 |
+
"from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"#We use Label Encoder\n",
|
| 150 |
+
"le = LabelEncoder()\n",
|
| 151 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 152 |
+
"for col in categorical_cols:\n",
|
| 153 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 154 |
+
" le = LabelEncoder()\n",
|
| 155 |
+
" df_clean[col] = le.fit_transform(df[col])\n",
|
| 156 |
+
"df_clean\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"#We have abandoned the bonus\n",
|
| 167 |
+
"#not_categorical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns\n",
|
| 168 |
+
"#We need different df\n",
|
| 169 |
+
"#df_objects = df_clean.drop(not_categorical_cols, axis= 1).copy()\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"#Time to one hot encode for BONUS\n",
|
| 172 |
+
"#df_encoded = ohe.fit_transform(df_objects)\n",
|
| 173 |
+
"#df_encoded = pd.DataFrame(df_encoded, columns= ohe.get_feature_names_out(df_objects.columns), index= df_objects.index)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"#Now to add the encoded df back to df\n",
|
| 176 |
+
"#df_modified = df_clean.drop(categorical_cols, axis= 1).copy()\n",
|
| 177 |
+
"#df_modified += df_encoded\n",
|
| 178 |
+
"#df_modified\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"#df_encoded = ohe.fit_transform(df_clean)\n",
|
| 181 |
+
"#df_encoded = pd.DataFrame(df_encoded, columns= ohe.get_feature_names_out(df_clean.columns), index= df_clean.index)"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task 5: Write your code here:\n",
|
| 191 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 192 |
+
"#X and y\n",
|
| 193 |
+
"X = df_clean.drop('Delivery_Time', axis= 1)\n",
|
| 194 |
+
"y = df[\"Delivery_Time\"]\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"#Lets split now\n",
|
| 198 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=67)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"#Scale data\n",
|
| 201 |
+
"scaler = StandardScaler()\n",
|
| 202 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
| 203 |
+
"X_test_scaled = scaler.transform(X_test)\n",
|
| 204 |
+
"\n"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"# Task 6: Write your code here:"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 1: Write your code here:\n",
|
| 223 |
+
"#Already split"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 233 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"models = {\n",
|
| 237 |
+
" \"Random Forest\": RandomForestClassifier(\n",
|
| 238 |
+
" n_estimators=200,\n",
|
| 239 |
+
" max_depth=10\n",
|
| 240 |
+
" )\n",
|
| 241 |
+
"}\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"n_splits = 5\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=67)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
|
| 249 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" # Get the train & test split for this fold\n",
|
| 252 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 253 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Train & Validate Models\n",
|
| 256 |
+
" for model_name, model in models.items():\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" print(f\"Training {model_name}...\")\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Fit the model on train data\n",
|
| 261 |
+
" model.fit(X_train, y_train)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Use the model to predict the test data\n",
|
| 264 |
+
" y_pred = model.predict(X_test)"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"cell_type": "code",
|
| 271 |
+
"metadata": {},
|
| 272 |
+
"source": [
|
| 273 |
+
"# Task 1: Write your code here:"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Task 2: Write your code here:"
|
| 283 |
+
],
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"outputs": []
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"source": [
|
| 291 |
+
"# Task Bonus: Write your code here:"
|
| 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/708/Q2.ipynb
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 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 |
+
"#More imports\n",
|
| 27 |
+
"import kagglehub\n",
|
| 28 |
+
"import pandas as pd\n",
|
| 29 |
+
"import torch\n",
|
| 30 |
+
"import torch.nn as nn\n",
|
| 31 |
+
"from torch.optim import AdamW\n",
|
| 32 |
+
"import matplotlib.pyplot as plt\n",
|
| 33 |
+
"import torch.nn.functional as F\n",
|
| 34 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 35 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 36 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"# Load Labels\n",
|
| 39 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 40 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"images = []\n",
|
| 43 |
+
"ages = []\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"# Load Images and Resize\n",
|
| 46 |
+
"print(\"Loading images...\")\n",
|
| 47 |
+
"for index, row in labels_df.iterrows():\n",
|
| 48 |
+
" img_name = row.iloc[0]\n",
|
| 49 |
+
" age = row.iloc[1]\n",
|
| 50 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 51 |
+
"\n",
|
| 52 |
+
" if os.path.exists(img_path):\n",
|
| 53 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 54 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 55 |
+
" images.append(img_array)\n",
|
| 56 |
+
" ages.append(age)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"X = np.array(images)\n",
|
| 59 |
+
"y = np.array(ages)\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 62 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"# Split Data\n",
|
| 65 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 68 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 69 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 70 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 80 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 81 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 82 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 83 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 84 |
+
"\n"
|
| 85 |
+
],
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": []
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"source": [
|
| 93 |
+
"# 2. Create TensorDataset objects\n",
|
| 94 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 95 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 96 |
+
"\n"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# 3. Create DataLoaders\n",
|
| 106 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 107 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 108 |
+
"\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# 4. Print shape of one batch\n",
|
| 118 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 119 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 120 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 121 |
+
],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# 5. Display sample images\n",
|
| 130 |
+
"# Get one batch of images and labels\n",
|
| 131 |
+
"images, labels = next(iter(train_loader))\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"# Display the first 6 images in the batch\n",
|
| 134 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"for i in range(6):\n",
|
| 137 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 140 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" plt.imshow(img)\n",
|
| 143 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 144 |
+
" plt.axis('off')\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"plt.tight_layout()\n",
|
| 147 |
+
"plt.show()\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 |
+
"\n",
|
| 159 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 160 |
+
" super(NN4Layer, self).__init__()\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # activation function for non-linearity\n",
|
| 171 |
+
" self.relu = nn.ReLU()\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" self.dropout = nn.Dropout(0.1)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Defines how input data flows through the network\n",
|
| 176 |
+
" def forward(self, x):\n",
|
| 177 |
+
" # Layer 1:\n",
|
| 178 |
+
" z1 = self.layer1(x)\n",
|
| 179 |
+
" a1 = self.relu(z1)\n",
|
| 180 |
+
" b1 = self.dropout(a1)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # Layer 2\n",
|
| 183 |
+
" z2 = self.layer2(b1)\n",
|
| 184 |
+
" a2 = self.relu(z2)\n",
|
| 185 |
+
" b2 = self.dropout(a2)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # Layer 3\n",
|
| 188 |
+
" z3 = self.layer3(b2)\n",
|
| 189 |
+
" a3 = self.relu(z3)\n",
|
| 190 |
+
" b3 = self.dropout(a3)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # Output layer\n",
|
| 193 |
+
" z4 = self.layer4(b3)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" return z4"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 2: Write your training loop here:\n",
|
| 205 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 206 |
+
" model.train().to(device)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" running_loss = 0.0\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 211 |
+
" # TODO: Move batch to the selected device\n",
|
| 212 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device) # <Replace None with your code>\n",
|
| 213 |
+
" y_batch = y_batch.to(device) #.float().view(-1, 1) # <Replace None with your code> [HINT: reshape to (-1, 1)]\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # TODO: Forward pass - get model predictions\n",
|
| 216 |
+
" outputs = model(X_batch) # <Replace None with your code>\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" # TODO: Compute loss using criterion\n",
|
| 219 |
+
" loss = criterion(outputs, y_batch) # <Replace None with your code>\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # TODO: Backward pass & optimization\n",
|
| 222 |
+
" # Step 1: Clear previous gradients\n",
|
| 223 |
+
" optimizer.zero_grad()\n",
|
| 224 |
+
" # Step 2: Compute gradients (backward pass)\n",
|
| 225 |
+
" loss.backward()\n",
|
| 226 |
+
" # Step 3: Update model parameters\n",
|
| 227 |
+
" optimizer.step()\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" running_loss += loss.item()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Calculate average loss over all batches\n",
|
| 232 |
+
" avg_loss = running_loss / len(train_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 3: Write your validation loop here:\n",
|
| 244 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 245 |
+
" model.eval()\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" running_loss = 0.0\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" #Disable gradient computation using torch.no_grad()\n",
|
| 250 |
+
" with torch.no_grad():\n",
|
| 251 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 252 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device) # <Replace None with your code>\n",
|
| 253 |
+
" y_batch = y_batch.to(device) #.float().view(-1, 1) # <Replace None with your code> [HINT: reshape to (-1, 1)]\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" #Forward pass - get model predictions\n",
|
| 256 |
+
" outputs = model(X_batch)\n",
|
| 257 |
+
" #Compute loss using criterion\n",
|
| 258 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" running_loss += loss.item()\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" return avg_loss"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"cell_type": "code",
|
| 271 |
+
"metadata": {},
|
| 272 |
+
"source": [
|
| 273 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 274 |
+
"# Device setup\n",
|
| 275 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 276 |
+
"print(\"Device:\", device, \"\\n\")\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Model parameters\n",
|
| 279 |
+
"input_dim = 3 * 36 * 36\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"hidden_dim = 256\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 285 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 288 |
+
"print(model)\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"# Calculate the total number of trainable parameters\n",
|
| 291 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 292 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"#Loss and optimizer\n",
|
| 295 |
+
"num_epochs = 20\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"learning_rate = 0.001\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"criterion = nn.MSELoss()\n",
|
| 300 |
+
"optimizer = AdamW(model.parameters(), learning_rate, weight_decay= 0.0001)"
|
| 301 |
+
],
|
| 302 |
+
"execution_count": null,
|
| 303 |
+
"outputs": []
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"cell_type": "code",
|
| 307 |
+
"metadata": {},
|
| 308 |
+
"source": [
|
| 309 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 310 |
+
"# Run Training\n",
|
| 311 |
+
"train_losses = []\n",
|
| 312 |
+
"val_losses = []\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"print('Starting Training...')\n",
|
| 315 |
+
"for epoch in range(num_epochs):\n",
|
| 316 |
+
" # TODO: Train one epoch using the train_one_epoch function\n",
|
| 317 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device) # <Replace None with your code>\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" # TODO: Validate using the validate function\n",
|
| 320 |
+
" val_loss = validate(model, criterion, test_loader, device) # <Replace None with your code>\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" train_losses.append(train_loss)\n",
|
| 323 |
+
" val_losses.append(val_loss)\n",
|
| 324 |
+
"\n",
|
| 325 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"print('Training Complete!')"
|
| 328 |
+
],
|
| 329 |
+
"execution_count": null,
|
| 330 |
+
"outputs": []
|
| 331 |
+
},
|
| 332 |
+
{
|
| 333 |
+
"cell_type": "code",
|
| 334 |
+
"metadata": {},
|
| 335 |
+
"source": [
|
| 336 |
+
"# Task 1: Write your code here:\n",
|
| 337 |
+
"# Plotting results\n",
|
| 338 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 341 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 342 |
+
"plt.title('Loss over Epochs')\n",
|
| 343 |
+
"plt.xlabel('Epoch')\n",
|
| 344 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 345 |
+
"plt.legend()\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"plt.tight_layout()\n",
|
| 348 |
+
"plt.show()"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 358 |
+
],
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"outputs": []
|
| 361 |
+
}
|
| 362 |
+
],
|
| 363 |
+
"metadata": {
|
| 364 |
+
"kernelspec": {
|
| 365 |
+
"display_name": "Python 3",
|
| 366 |
+
"name": "python3"
|
| 367 |
+
},
|
| 368 |
+
"language_info": {
|
| 369 |
+
"name": "python"
|
| 370 |
+
}
|
| 371 |
+
},
|
| 372 |
+
"nbformat": 4,
|
| 373 |
+
"nbformat_minor": 0
|
| 374 |
+
}
|
submissions_extracted/708/Q3.ipynb
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"import kagglehub\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 |
+
"df_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 33 |
+
"df = pd.read_csv(df_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.head()"
|
| 44 |
+
],
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"# Task 3: Write your code here:\n",
|
| 53 |
+
"df.info()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 4: Write your code here:\n",
|
| 63 |
+
"df.describe()"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 1: Write your code here:\n",
|
| 73 |
+
"df = df.fillna(0)\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"# Missing values\n",
|
| 76 |
+
"print(\"Missing values:\")\n",
|
| 77 |
+
"print(df.isnull().sum())"
|
| 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 |
+
"df = df.drop_duplicates()"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 3: Write your code here:\n",
|
| 97 |
+
"#All float and int\n",
|
| 98 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# Task 4: Write your code here:\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"# Scale features later\n",
|
| 110 |
+
"\n"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# Task 5: Write your code here:"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# Task 1: Write your code here:\n",
|
| 129 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"X = df.drop('Target', axis= 1)\n",
|
| 132 |
+
"y = df['Target']\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"scaler = StandardScaler()\n",
|
| 135 |
+
"X = scaler.fit_transform(X)\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 145 |
+
"from catboost import CatBoostClassifier\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"models = {\n",
|
| 148 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 149 |
+
" verbose=0,\n",
|
| 150 |
+
" n_estimators=200,\n",
|
| 151 |
+
" max_depth=4\n",
|
| 152 |
+
" )\n",
|
| 153 |
+
"}\n",
|
| 154 |
+
"n_splits = 3 # K=3 Folds\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=67)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
|
| 159 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" # Get the train & test split for this fold\n",
|
| 162 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 163 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # Train & Validate Models\n",
|
| 166 |
+
" for model_name, model in models.items():\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" print(f\"Training {model_name}...\")\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # Fit the model on train data\n",
|
| 171 |
+
" model.fit(X_train, y_train)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # Use the model to predict the test data\n",
|
| 174 |
+
" y_pred = model.predict(X_test)"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# Task 1: Write your code here:"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 2: Write your code here:\n",
|
| 193 |
+
"#I believe its column D_39\n",
|
| 194 |
+
"\n"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"# Task Bonus: Write your code here:\n",
|
| 204 |
+
"X = df['D_39']\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
|
| 207 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" # Get the train & test split for this fold\n",
|
| 210 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 211 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" # Train & Validate Models\n",
|
| 214 |
+
" for model_name, model in models.items():\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" print(f\"Training {model_name}...\")\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" # Fit the model on train data\n",
|
| 219 |
+
" model.fit(X_train, y_train)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Use the model to predict the test data\n",
|
| 222 |
+
" y_pred = model.predict(X_test)\n",
|
| 223 |
+
"\n"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
}
|
| 228 |
+
],
|
| 229 |
+
"metadata": {
|
| 230 |
+
"kernelspec": {
|
| 231 |
+
"display_name": "Python 3",
|
| 232 |
+
"name": "python3"
|
| 233 |
+
},
|
| 234 |
+
"language_info": {
|
| 235 |
+
"name": "python"
|
| 236 |
+
}
|
| 237 |
+
},
|
| 238 |
+
"nbformat": 4,
|
| 239 |
+
"nbformat_minor": 0
|
| 240 |
+
}
|
submissions_extracted/709/Q1.ipynb
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# Core data manipulation\n",
|
| 8 |
+
"import numpy as np\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"from scipy import stats\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"# Visualization\n",
|
| 14 |
+
"import matplotlib.pyplot as plt\n",
|
| 15 |
+
"import seaborn as sns\n",
|
| 16 |
+
"%matplotlib inline\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Machine Learning\n",
|
| 19 |
+
"from sklearn.model_selection import train_test_split, KFold, StratifiedKFold\n",
|
| 20 |
+
"from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder\n",
|
| 21 |
+
"from sklearn.metrics import mean_squared_error, r2_score, accuracy_score\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"# Models\n",
|
| 24 |
+
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
| 25 |
+
"from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\n",
|
| 26 |
+
"from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n",
|
| 27 |
+
"from sklearn.svm import SVR, SVC\n",
|
| 28 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 29 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"import kagglehub\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"# Download latest version\n",
|
| 41 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"print(\"Path to dataset files:\", path)"
|
| 44 |
+
],
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"# Task 1: Write your code here:\n",
|
| 53 |
+
"df_delivery = df = pd.read_csv(f\"{path}/Q1_data.csv\")"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 2: Write your code here:\n",
|
| 63 |
+
"df_delivery.head()"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 3: Write your code here:\n",
|
| 73 |
+
"df_delivery.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 |
+
"df_delivery.describe()"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 5: Write your code here:\n",
|
| 93 |
+
"# Delivery_Time distribution (target variable)\n",
|
| 94 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 95 |
+
"plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 96 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 97 |
+
"plt.xlabel('Price')\n",
|
| 98 |
+
"plt.ylabel('Frequency')\n",
|
| 99 |
+
"plt.show()"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 1: Write your code here:\n",
|
| 109 |
+
"df_delivery.drop(columns=['Order_ID'])"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# Task 2: Write your code here:\n",
|
| 119 |
+
"missing_percentage = (df_delivery.isnull().sum() / len(df_delivery)) * 100\n",
|
| 120 |
+
"missing_data = pd.DataFrame({\n",
|
| 121 |
+
" 'Column': missing_percentage.index,\n",
|
| 122 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 123 |
+
" })\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 126 |
+
"missing_data"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"#for col in ['Delivery_Time', 'Courier_Experience_yrs']:\n",
|
| 136 |
+
" #df['col'].fillna(df['col'].mean())\n",
|
| 137 |
+
"#cols = ['Courier_Experience_yrs', 'Delivery_Time']\n",
|
| 138 |
+
"#df_clean = df_delivery[cols].copy()\n",
|
| 139 |
+
"#df_clean = df_clean.fillna(subset=['Courier_Experience_yrs', 'Delivery_Time']).mean()"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n",
|
| 149 |
+
"cols = ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
|
| 150 |
+
"df_clean = df_delivery[cols].copy()\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"# Drop rows where target (price) or key features are missing - can't predict without them\n",
|
| 153 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 154 |
+
"df_clean = df_clean.dropna(subset=['Delivery_Time', 'Courier_Experience_yrs', 'Time_of_Day','Traffic_Level','Weather' ])\n",
|
| 155 |
+
"print(f\"After dropping missing : {df_clean.shape}\")"
|
| 156 |
+
],
|
| 157 |
+
"execution_count": null,
|
| 158 |
+
"outputs": []
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"cell_type": "code",
|
| 162 |
+
"metadata": {},
|
| 163 |
+
"source": [
|
| 164 |
+
"# Task 3: Write your code here:\n",
|
| 165 |
+
"# one way to do it\n",
|
| 166 |
+
"df_clean.drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"# other way\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 |
+
"df_clean.head()"
|
| 189 |
+
],
|
| 190 |
+
"execution_count": null,
|
| 191 |
+
"outputs": []
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"# Task 4\n",
|
| 198 |
+
"# Encode categorical columns - converts text to integers\n",
|
| 199 |
+
"categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day']\n",
|
| 200 |
+
"for col in categorical_cols:\n",
|
| 201 |
+
" le = LabelEncoder()\n",
|
| 202 |
+
" df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"df_clean.head()"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"# Task 5\n",
|
| 214 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"print('data before scaling:\\n', df_clean) #show before scaling\n",
|
| 217 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 218 |
+
"data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 6: Write your code here:\n",
|
| 230 |
+
"# Target distribution\n",
|
| 231 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 232 |
+
" print(\"Target Distribution:\")\n",
|
| 233 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 234 |
+
" sns.countplot(x=df[target_column])\n",
|
| 235 |
+
" plt.title(\"Target Distribution\")\n",
|
| 236 |
+
" plt.show()\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"check_target_imbalance(df, \"Delivery_Time\")\n"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 1: Write your code here:\n",
|
| 248 |
+
"from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
|
| 249 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 250 |
+
"import numpy as np\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"# Sample data\n",
|
| 253 |
+
"X = df_clean[without the target col]\n",
|
| 254 |
+
"y = df_clean[only the target col]\n",
|
| 255 |
+
"#I am really sorry I know the approach But Im just overwhelmed Im having trouples with implemnting it\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"# KFold Cross-Validation\n",
|
| 258 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 259 |
+
"model = LogisticRegression()\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"# Get scores for each fold\n",
|
| 262 |
+
"scores = cross_val_score(model, X, y, cv=kfold, scoring='accuracy')\n",
|
| 263 |
+
"print(\"KFold scores:\", scores)\n",
|
| 264 |
+
"print(f\"Mean accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})\")\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"# StratifiedKFold (for imbalanced data)\n",
|
| 267 |
+
"skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 268 |
+
"scores_strat = cross_val_score(model, X, y, cv=skfold, scoring='accuracy')\n",
|
| 269 |
+
"print(\"\\nStratifiedKFold scores:\", scores_strat)\n",
|
| 270 |
+
"print(f\"Mean accuracy: {scores_strat.mean():.3f}\")"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "code",
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"source": [
|
| 279 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 280 |
+
"rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n",
|
| 281 |
+
"rf.fit(X_train, y_train)\n",
|
| 282 |
+
"print(\"Random Forest R²:\", rf.score(X_test, y_test))"
|
| 283 |
+
],
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"outputs": []
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"source": [
|
| 291 |
+
"# Task 1: Write your code here:"
|
| 292 |
+
],
|
| 293 |
+
"execution_count": null,
|
| 294 |
+
"outputs": []
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"cell_type": "code",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"source": [
|
| 300 |
+
"# Task 2: Write your code here:"
|
| 301 |
+
],
|
| 302 |
+
"execution_count": null,
|
| 303 |
+
"outputs": []
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"cell_type": "code",
|
| 307 |
+
"metadata": {},
|
| 308 |
+
"source": [
|
| 309 |
+
"# Task Bonus: Write your code here:"
|
| 310 |
+
],
|
| 311 |
+
"execution_count": null,
|
| 312 |
+
"outputs": []
|
| 313 |
+
}
|
| 314 |
+
],
|
| 315 |
+
"metadata": {
|
| 316 |
+
"kernelspec": {
|
| 317 |
+
"display_name": "Python 3",
|
| 318 |
+
"name": "python3"
|
| 319 |
+
},
|
| 320 |
+
"language_info": {
|
| 321 |
+
"name": "python"
|
| 322 |
+
}
|
| 323 |
+
},
|
| 324 |
+
"nbformat": 4,
|
| 325 |
+
"nbformat_minor": 0
|
| 326 |
+
}
|
submissions_extracted/709/Q2.ipynb
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"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 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 90 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 91 |
+
"\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 3. Create DataLoaders\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"from torch.utils.data import DataLoader\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"# DataLoader for training data\n",
|
| 106 |
+
"train_loader = DataLoader(\n",
|
| 107 |
+
" train_dataset,\n",
|
| 108 |
+
" batch_size=32,\n",
|
| 109 |
+
" shuffle=True,\n",
|
| 110 |
+
" num_workers=2\n",
|
| 111 |
+
")\n",
|
| 112 |
+
"# DataLoader for test/validation data\n",
|
| 113 |
+
"test_loader = DataLoader(\n",
|
| 114 |
+
" test_dataset,\n",
|
| 115 |
+
" batch_size=32,\n",
|
| 116 |
+
" shuffle=False,\n",
|
| 117 |
+
" num_workers=2\n",
|
| 118 |
+
")"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# 4. Print shape of one batch\n",
|
| 128 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 129 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 130 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# 5. Display sample images\n",
|
| 140 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 143 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 144 |
+
"\n"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 1: Write your model class here:\n",
|
| 154 |
+
"import torch\n",
|
| 155 |
+
"import torch.nn as nn\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"# Create a linear layer: 3 input features -> 1 output\n",
|
| 158 |
+
"linear = nn.Linear(in_features=3, out_features=1)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"# Example input: batch of 4 samples, each with 3 features\n",
|
| 161 |
+
"x = torch.randn(4, 3)\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"# Forward through the layer\n",
|
| 164 |
+
"y = linear(x)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n",
|
| 167 |
+
"print(\"Output shape:\", y.shape) # torch.Size([4, 1])"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 2: Write your training loop here:\n",
|
| 177 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 178 |
+
" # Set the model to training mode\n",
|
| 179 |
+
" model.train()\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" running_loss = 0.0\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 184 |
+
" # Move batch to the selected device\n",
|
| 185 |
+
" X_batch = X_batch.to(device)\n",
|
| 186 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" # Forward pass\n",
|
| 189 |
+
" outputs = model(X_batch)\n",
|
| 190 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # Backward pass & optimization\n",
|
| 193 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 194 |
+
" loss.backward() # Compute gradients\n",
|
| 195 |
+
" optimizer.step() # Update model parameters\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" running_loss += loss.item()\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" # Average loss over all batches\n",
|
| 200 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" return avg_loss"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 3: Write your validation loop here:\n",
|
| 212 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 213 |
+
" # Set the model to evaluation mode\n",
|
| 214 |
+
" model.eval()\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" running_loss = 0.0\n",
|
| 217 |
+
" correct = 0\n",
|
| 218 |
+
" total = 0\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" with torch.no_grad(): # Disable gradient computation\n",
|
| 221 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 222 |
+
" # Move batch to the selected device\n",
|
| 223 |
+
" X_batch = X_batch.to(device)\n",
|
| 224 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # Forward pass\n",
|
| 227 |
+
" outputs = model(X_batch)\n",
|
| 228 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 229 |
+
" running_loss += loss.item()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Binary predictions\n",
|
| 232 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" # Accuracy calculation\n",
|
| 235 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 236 |
+
" total += y_batch.size(0)\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 239 |
+
" accuracy = correct / total\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" return avg_loss, accuracy"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "code",
|
| 248 |
+
"metadata": {},
|
| 249 |
+
"source": [
|
| 250 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 251 |
+
"#already defined ig\n",
|
| 252 |
+
"#Parameters\n",
|
| 253 |
+
"#model – The neural network to be trained.\n",
|
| 254 |
+
"#optimizer – Updates model parameters (e.g., SGD, Adam).\n",
|
| 255 |
+
"#criterion – Loss function, depends on the task.\n",
|
| 256 |
+
"#train_loader – PyTorch DataLoader that provides batches of training data.\n",
|
| 257 |
+
"#device – Device used for computation (cpu or cuda).\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"[ ]\n"
|
| 260 |
+
],
|
| 261 |
+
"execution_count": null,
|
| 262 |
+
"outputs": []
|
| 263 |
+
},
|
| 264 |
+
{
|
| 265 |
+
"cell_type": "code",
|
| 266 |
+
"metadata": {},
|
| 267 |
+
"source": [
|
| 268 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 269 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 270 |
+
" # Set the model to training mode\n",
|
| 271 |
+
" model.train()\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" running_loss = 0.0\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 276 |
+
" # Move batch to the selected device\n",
|
| 277 |
+
" X_batch = X_batch.to(device)\n",
|
| 278 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Forward pass\n",
|
| 281 |
+
" outputs = model(X_batch)\n",
|
| 282 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" # Backward pass & optimization\n",
|
| 285 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 286 |
+
" loss.backward() # Compute gradients\n",
|
| 287 |
+
" optimizer.step() # Update model parameters\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" running_loss += loss.item()\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" # Average loss over all batches\n",
|
| 292 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
" return avg_loss"
|
| 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 |
+
"import matplotlib.pyplot as plt\n",
|
| 305 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 308 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 309 |
+
"plt.title('Loss over Epochs')\n",
|
| 310 |
+
"plt.xlabel('Epoch')\n",
|
| 311 |
+
"plt.ylabel('Loss')\n",
|
| 312 |
+
"plt.legend()\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"plt.tight_layout()\n",
|
| 315 |
+
"plt.show()"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"# Task 2 (Bonus): Write your code here:\n"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
}
|
| 329 |
+
],
|
| 330 |
+
"metadata": {
|
| 331 |
+
"kernelspec": {
|
| 332 |
+
"display_name": "Python 3",
|
| 333 |
+
"name": "python3"
|
| 334 |
+
},
|
| 335 |
+
"language_info": {
|
| 336 |
+
"name": "python"
|
| 337 |
+
}
|
| 338 |
+
},
|
| 339 |
+
"nbformat": 4,
|
| 340 |
+
"nbformat_minor": 0
|
| 341 |
+
}
|
submissions_extracted/709/Q3.ipynb
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"from sklearn.model_selection import train_test_split, KFold, cross_val_score\n",
|
| 13 |
+
"from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n",
|
| 14 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
|
| 15 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 16 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 17 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 18 |
+
"from sklearn.svm import SVC\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"# Download latest version\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"print(\"Path to dataset files:\", path)"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"# Task 1: Write your code here:\n",
|
| 38 |
+
"df_g = df = pd.read_csv(f\"{path}/Q3_data.csv\")"
|
| 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_g.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_g.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_g.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 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 79 |
+
"print(df.isnull().sum())\n",
|
| 80 |
+
"missing_percentage = (df_g.isnull().sum() / len(df_g)) * 100\n",
|
| 81 |
+
"missing_data = pd.DataFrame({\n",
|
| 82 |
+
" 'Column': missing_percentage.index,\n",
|
| 83 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 84 |
+
" })\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 87 |
+
"missing_data"
|
| 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 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"#1. DecisionTreeRegressor (for Regression)\n",
|
| 106 |
+
"What it does: Predicts numbers by splitting data with if-then rules\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"# Create tree\n",
|
| 111 |
+
"tree_reg = DecisionTreeRegressor(\n",
|
| 112 |
+
" max_depth=3, # Control tree depth (prevent overfitting)\n",
|
| 113 |
+
" min_samples_split=5, # Minimum samples to split node\n",
|
| 114 |
+
" min_samples_leaf=2, # Minimum samples in leaf\n",
|
| 115 |
+
" random_state=42 # Reproducible trees\n",
|
| 116 |
+
")\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"# Fit and predict\n",
|
| 119 |
+
"tree_reg.fit(X_train, y_train)\n",
|
| 120 |
+
"predictions = tree_reg.predict(X_test) # Continuous numbers\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"#When to use:\n",
|
| 123 |
+
"Non-linear relationships\n",
|
| 124 |
+
"Need interpretability\n",
|
| 125 |
+
"Want feature importance"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 3: Write your code here:\n",
|
| 135 |
+
"2.DecisionTreeClassifier (for Classification)\n",
|
| 136 |
+
"What it does: Predicts categories using if-then rules\n",
|
| 137 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"tree_clf = DecisionTreeClassifier(\n",
|
| 140 |
+
" max_depth=4, # Shallower = simpler, less overfitting\n",
|
| 141 |
+
" criterion='gini', # 'gini' or 'entropy' for split quality\n",
|
| 142 |
+
" random_state=42\n",
|
| 143 |
+
")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"tree_clf.fit(X_train, y_train)\n",
|
| 146 |
+
"predictions = tree_clf.predict(X_test) # Class labels (0/1, etc.)\n",
|
| 147 |
+
"probabilities = tree_clf.predict_proba(X_test) # Class probabilities\n",
|
| 148 |
+
"\n"
|
| 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 |
+
"# Split X_train and y_train into training and validation sets for the current fold\n",
|
| 159 |
+
" X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n",
|
| 160 |
+
" y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" # Train the current model\n",
|
| 163 |
+
" model.fit(X_train_fold, y_train_fold)\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # Generate predictions (probabilities) on the validation set\n",
|
| 166 |
+
" y_pred_proba = model.predict_proba(X_val_fold)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # Convert y_val_fold (true labels) into a one-hot encoded format\n",
|
| 169 |
+
" y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # Calculate categorical cross-entropy loss for the current fold\n",
|
| 172 |
+
" loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n",
|
| 173 |
+
" fold_losses.append(loss)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Calculate the average loss for the model\n",
|
| 176 |
+
" avg_loss = np.mean(fold_losses)\n",
|
| 177 |
+
" model_losses[model_name] = avg_loss\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Print the average cross-validation loss for the current model\n",
|
| 180 |
+
" print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"print(\"\\nAll models trained and evaluated. Stored average losses:\")\n",
|
| 183 |
+
"print(model_losses)"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 5: Write your code here:\n",
|
| 193 |
+
"# Split X_train and y_train into training and validation sets for the current fold\n",
|
| 194 |
+
" X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n",
|
| 195 |
+
" y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Train the current model\n",
|
| 198 |
+
" model.fit(X_train_fold, y_train_fold)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Generate predictions (probabilities) on the validation set\n",
|
| 201 |
+
" y_pred_proba = model.predict_proba(X_val_fold)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" # Convert y_val_fold (true labels) into a one-hot encoded format\n",
|
| 204 |
+
" y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # Calculate categorical cross-entropy loss for the current fold\n",
|
| 207 |
+
" loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n",
|
| 208 |
+
" fold_losses.append(loss)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Calculate the average loss for the model\n",
|
| 211 |
+
" avg_loss = np.mean(fold_losses)\n",
|
| 212 |
+
" model_losses[model_name] = avg_loss\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" # Print the average cross-validation loss for the current model\n",
|
| 215 |
+
" print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"print(\"\\nAll models trained and evaluated. Stored average losses:\")\n",
|
| 218 |
+
"print(model_losses)"
|
| 219 |
+
],
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"outputs": []
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"source": [
|
| 227 |
+
"# Task 1: Write your code here:"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# Task 1: Write your code here:"
|
| 246 |
+
],
|
| 247 |
+
"execution_count": null,
|
| 248 |
+
"outputs": []
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"# Task 2: Write your code here:"
|
| 255 |
+
],
|
| 256 |
+
"execution_count": null,
|
| 257 |
+
"outputs": []
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"metadata": {},
|
| 262 |
+
"source": [
|
| 263 |
+
"# Task Bonus: Write your code here:"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
}
|
| 268 |
+
],
|
| 269 |
+
"metadata": {
|
| 270 |
+
"kernelspec": {
|
| 271 |
+
"display_name": "Python 3",
|
| 272 |
+
"name": "python3"
|
| 273 |
+
},
|
| 274 |
+
"language_info": {
|
| 275 |
+
"name": "python"
|
| 276 |
+
}
|
| 277 |
+
},
|
| 278 |
+
"nbformat": 4,
|
| 279 |
+
"nbformat_minor": 0
|
| 280 |
+
}
|
submissions_extracted/71/Q1.ipynb
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
"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')\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# Task 1: Write your code here:\n",
|
| 34 |
+
"df = pd.read_csv(delivrey_path)\n"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# Task 2: Write your code here:\n",
|
| 44 |
+
"print(f\"Dataset shape: {df_delivery.shape}\")\n",
|
| 45 |
+
"df_delivery.head()\n"
|
| 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_delivery.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('delivrey')"
|
| 66 |
+
],
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"# Task 5: Write your code here:\n",
|
| 75 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 76 |
+
"plt.hist(df_delivery.time['attack'].dropna(), bins=30, edgecolor='black')\n",
|
| 77 |
+
"plt.title('Attack Distribution')\n",
|
| 78 |
+
"plt.xlabel('Attack')\n",
|
| 79 |
+
"plt.ylabel('Frequency')\n",
|
| 80 |
+
"plt.show()"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 1: Write your code here:\n",
|
| 90 |
+
"X = df.drop(\"delivery time\",axis=1)\n",
|
| 91 |
+
"y = df['delivery time']"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# Task 2: Write your code here:\n",
|
| 101 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 102 |
+
"print(df.isnull().sum())"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 3: Write your code here:\n",
|
| 112 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 113 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 114 |
+
"if duplicate_rows > 0:\n",
|
| 115 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 116 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 117 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 118 |
+
"else:\n",
|
| 119 |
+
" print(\"No duplicate rows found.\")"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# Task 4: Write your code here:"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# Task 5: Write your code here:"
|
| 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:"
|
| 156 |
+
],
|
| 157 |
+
"execution_count": null,
|
| 158 |
+
"outputs": []
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"cell_type": "code",
|
| 162 |
+
"metadata": {},
|
| 163 |
+
"source": [
|
| 164 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 1: Write your code here:"
|
| 174 |
+
],
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"outputs": []
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "code",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"source": [
|
| 182 |
+
"# Task 2: Write your code here:"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Task Bonus: Write your code here:"
|
| 192 |
+
],
|
| 193 |
+
"execution_count": null,
|
| 194 |
+
"outputs": []
|
| 195 |
+
}
|
| 196 |
+
],
|
| 197 |
+
"metadata": {
|
| 198 |
+
"kernelspec": {
|
| 199 |
+
"display_name": "Python 3",
|
| 200 |
+
"name": "python3"
|
| 201 |
+
},
|
| 202 |
+
"language_info": {
|
| 203 |
+
"name": "python"
|
| 204 |
+
}
|
| 205 |
+
},
|
| 206 |
+
"nbformat": 4,
|
| 207 |
+
"nbformat_minor": 0
|
| 208 |
+
}
|
submissions_extracted/71/Q2.ipynb
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.values, dtype=torch.float32)\n",
|
| 70 |
+
"X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
|
| 71 |
+
"y_train = torch.tensor(y_train.values, dtype=torch.float32)\n",
|
| 72 |
+
"y_test = torch.tensor(y_test.values, dtype=torch.float32)\n"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# 2. Create TensorDataset objects\n",
|
| 82 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 83 |
+
"test_dataset = TensorDataset(X_test, y_test)"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# 3. Create DataLoaders\n",
|
| 93 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 94 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# 4. Print shape of one batch\n",
|
| 104 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 105 |
+
"print(\"Test dataset:\", len(test_dataset))"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# 5. Display sample images\n",
|
| 115 |
+
"\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 1: Write your model class here:\n",
|
| 125 |
+
"class NN4Layer(nn.Module):\n",
|
| 126 |
+
"\n",
|
| 127 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 128 |
+
" super(NN4Layer, self).__init__()\n",
|
| 129 |
+
"\n",
|
| 130 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 131 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 132 |
+
"\n",
|
| 133 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 134 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 137 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 140 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" # ReLU activation for non-linearity\n",
|
| 143 |
+
" self.relu = nn.ReLU()\n",
|
| 144 |
+
"\n",
|
| 145 |
+
" # Defines how input data flows through the network\n",
|
| 146 |
+
" def forward(self, x):\n",
|
| 147 |
+
" # First hidden layer\n",
|
| 148 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 149 |
+
"\n",
|
| 150 |
+
" # Second hidden layer\n",
|
| 151 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 152 |
+
"\n",
|
| 153 |
+
" # Third hidden layer\n",
|
| 154 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" # Output layer (raw scores / logits)\n",
|
| 157 |
+
" output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" return output\n",
|
| 160 |
+
"\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 2: Write your training loop here:"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 3: Write your validation loop here:"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 5: Start training for 20 epochs:"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# Task 1: Write your code here:"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
}
|
| 219 |
+
],
|
| 220 |
+
"metadata": {
|
| 221 |
+
"kernelspec": {
|
| 222 |
+
"display_name": "Python 3",
|
| 223 |
+
"name": "python3"
|
| 224 |
+
},
|
| 225 |
+
"language_info": {
|
| 226 |
+
"name": "python"
|
| 227 |
+
}
|
| 228 |
+
},
|
| 229 |
+
"nbformat": 4,
|
| 230 |
+
"nbformat_minor": 0
|
| 231 |
+
}
|
submissions_extracted/71/Q3.ipynb
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
"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')\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(\"Path to dataset files:\", path)"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 1: Write your code here:"
|
| 37 |
+
],
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"outputs": []
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Task 2: Write your code here:"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 3: Write your code here:"
|
| 55 |
+
],
|
| 56 |
+
"execution_count": null,
|
| 57 |
+
"outputs": []
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"source": [
|
| 63 |
+
"# Task 4: Write your code here:"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 1: Write your code here:"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 2: Write your code here:"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# Task 3: Write your code here:"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 4: Write your code here:"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 5: Write your code here:"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# Task 1: Write your code here:"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 1: Write your code here:"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 2: Write your code here:"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task Bonus: Write your code here:"
|
| 154 |
+
],
|
| 155 |
+
"execution_count": null,
|
| 156 |
+
"outputs": []
|
| 157 |
+
}
|
| 158 |
+
],
|
| 159 |
+
"metadata": {
|
| 160 |
+
"kernelspec": {
|
| 161 |
+
"display_name": "Python 3",
|
| 162 |
+
"name": "python3"
|
| 163 |
+
},
|
| 164 |
+
"language_info": {
|
| 165 |
+
"name": "python"
|
| 166 |
+
}
|
| 167 |
+
},
|
| 168 |
+
"nbformat": 4,
|
| 169 |
+
"nbformat_minor": 0
|
| 170 |
+
}
|
submissions_extracted/710/Q1.ipynb
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 pandas as pd\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"print(f\"Shape: {df.shape}\")\n",
|
| 27 |
+
"df.head()"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 2: Write your code here:\n",
|
| 37 |
+
"df.head()"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 3: Write your code here:\n",
|
| 47 |
+
"df.info()"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 4: Write your code here:\n",
|
| 57 |
+
"df.describe()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"# Task 5: Write your code here:\n",
|
| 67 |
+
"import matplotlib.pyplot as plt\n",
|
| 68 |
+
"from sklearn.linear_model import LinearRegression\n",
|
| 69 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 70 |
+
"plt.show()"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 1: Write your code here:\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"df=df.drop(columns='Order_ID')\n"
|
| 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 |
+
"\n",
|
| 92 |
+
"stat_cols=['Distance_km','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time','Time_of_Day','Traffic_Level','Weather']\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"df_c = df.dropna(subset=stat_cols)\n",
|
| 96 |
+
"print(f\"Shape after cleaning: {df_c.shape}\")\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"print(\"Missing values:\")\n",
|
| 99 |
+
"print(df_c.isnull().sum())"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 3: Write your code here:\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"def check_duplicates(df):\n",
|
| 111 |
+
" duplicates = df.duplicated().sum()\n",
|
| 112 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 113 |
+
" if duplicates > 0:\n",
|
| 114 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 115 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 116 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 117 |
+
" else:\n",
|
| 118 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"check_duplicates(df_c)\n",
|
| 121 |
+
"df_c.drop_duplicates(inplace=True)"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 4: Write your code here:\n",
|
| 131 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"categ_feats = df_c.select_dtypes(\"object\").columns\n",
|
| 134 |
+
"for cat in categ_feats:\n",
|
| 135 |
+
" le = LabelEncoder()\n",
|
| 136 |
+
" df_c[cat] = le.fit_transform(df_c[cat])\n"
|
| 137 |
+
],
|
| 138 |
+
"execution_count": null,
|
| 139 |
+
"outputs": []
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"cell_type": "code",
|
| 143 |
+
"metadata": {},
|
| 144 |
+
"source": [
|
| 145 |
+
"# Task 5: Write your code here:\n",
|
| 146 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"print('data before scaling:\\n', df_c) #show before scaling\n",
|
| 149 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 150 |
+
"df_c = standard_scaler.fit_transform(df_c) # Apply fit_transform\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"print('\\nData after scaling:\\n', df_c) #show after scaling"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 6: Write your code here:\n",
|
| 162 |
+
"#not need"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"# Task 1: Write your code here:\n",
|
| 172 |
+
"import numpy as np\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"np.random.seed(42)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n",
|
| 177 |
+
"y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n",
|
| 181 |
+
"y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"X, y = X_clf.copy(), y_clf.copy()"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 194 |
+
"from sklearn.model_selection import KFold\n",
|
| 195 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 196 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 197 |
+
"import numpy as np\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"# Use previously generated random data (example: regression data)\n",
|
| 200 |
+
"X, y = X, y\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"# Define K-Fold Cross Validation\n",
|
| 203 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"# Iterate through folds\n",
|
| 206 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), 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 |
+
" # print shapes\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 |
+
" print(\"-\" * 30)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 219 |
+
" class_weight='balanced', random_state=42)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"model.fit(X_train, y_train)\n",
|
| 222 |
+
"print(\"Model trained!\")\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"y_pred = model.predict(X_test)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 227 |
+
"print('mae =',mae)\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"mae_scores = []\n",
|
| 232 |
+
"rmse_scores = []\n",
|
| 233 |
+
"\n"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 1: Write your code here:\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"f=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
|
| 245 |
+
"feature_importance = pd.DataFrame({\n",
|
| 246 |
+
" 'feature': f,\n",
|
| 247 |
+
" 'importance': model.feature_importances_\n",
|
| 248 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 251 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 252 |
+
"plt.xlabel('Importance')\n",
|
| 253 |
+
"plt.title('Feature Importance')\n",
|
| 254 |
+
"plt.gca().invert_yaxis()\n",
|
| 255 |
+
"plt.show()"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task 2: Write your code here:\n",
|
| 265 |
+
"plt.hist(y_pred, bins=30, edgecolor='black')\n",
|
| 266 |
+
"plt.show()"
|
| 267 |
+
],
|
| 268 |
+
"execution_count": null,
|
| 269 |
+
"outputs": []
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": [
|
| 275 |
+
"# Task Bonus: Write your code here:"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
}
|
| 280 |
+
],
|
| 281 |
+
"metadata": {
|
| 282 |
+
"kernelspec": {
|
| 283 |
+
"display_name": "Python 3",
|
| 284 |
+
"name": "python3"
|
| 285 |
+
},
|
| 286 |
+
"language_info": {
|
| 287 |
+
"name": "python"
|
| 288 |
+
}
|
| 289 |
+
},
|
| 290 |
+
"nbformat": 4,
|
| 291 |
+
"nbformat_minor": 0
|
| 292 |
+
}
|
submissions_extracted/710/Q2.ipynb
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 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 |
+
"\n",
|
| 27 |
+
"# Download latest version\n",
|
| 28 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-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 |
+
"import os\n",
|
| 40 |
+
"import pandas as pd\n",
|
| 41 |
+
"import numpy as np\n",
|
| 42 |
+
"from PIL import Image\n",
|
| 43 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"# Load Labels\n",
|
| 46 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 47 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"images = []\n",
|
| 50 |
+
"ages = []\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"# Load Images and Resize\n",
|
| 53 |
+
"print(\"Loading images...\")\n",
|
| 54 |
+
"for index, row in labels_df.iterrows():\n",
|
| 55 |
+
" img_name = row.iloc[0]\n",
|
| 56 |
+
" age = row.iloc[1]\n",
|
| 57 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
" if os.path.exists(img_path):\n",
|
| 60 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 61 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 62 |
+
" images.append(img_array)\n",
|
| 63 |
+
" ages.append(age)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"X = np.array(images)\n",
|
| 66 |
+
"y = np.array(ages)\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 69 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Split Data\n",
|
| 72 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 75 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 76 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 77 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 87 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 88 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 89 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 90 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# 2. Create TensorDataset objects\n",
|
| 100 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 101 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 102 |
+
"\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# 3. Create DataLoaders\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 114 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# 4. Print shape of one batch\n",
|
| 124 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 125 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 126 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# 5. Display sample images\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"images= next(iter(train_loader))\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"# Display the first 6 images in the batch\n",
|
| 140 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"for i in range(2):\n",
|
| 143 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"\n",
|
| 146 |
+
" img = images[i].view(32,-1)\n",
|
| 147 |
+
"\n",
|
| 148 |
+
" plt.imshow(img)\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"plt.tight_layout()\n",
|
| 151 |
+
"plt.show()"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 1: Write your model class here:\n",
|
| 161 |
+
"class NN4Layer(nn.Module):\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 164 |
+
" super(NN4Layer, self).__init__()\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 167 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 170 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 173 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 176 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" # ReLU activation for non-linearity\n",
|
| 179 |
+
" self.relu = nn.ReLU()\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # Defines how input data flows through the network\n",
|
| 182 |
+
" def forward(self, x):\n",
|
| 183 |
+
" # First hidden layer\n",
|
| 184 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Second hidden layer\n",
|
| 187 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # Third hidden layer\n",
|
| 190 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" output = self.layer4(a3)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" return output"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 2: Write your training loop here:\n",
|
| 205 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 206 |
+
" # Set the model to training mode\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 |
+
" # Move batch to the selected device\n",
|
| 213 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 214 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Forward pass (outputs are logits)\n",
|
| 217 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 218 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Backward pass & optimization\n",
|
| 221 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 222 |
+
" loss.backward() # Compute gradients\n",
|
| 223 |
+
" optimizer.step() # Update model parameters\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" running_loss += loss.item()\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Average loss over all batches\n",
|
| 228 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" return avg_loss\n"
|
| 231 |
+
],
|
| 232 |
+
"execution_count": null,
|
| 233 |
+
"outputs": []
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "code",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": [
|
| 239 |
+
"# Task 3: Write your validation loop here:\n",
|
| 240 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 241 |
+
" # Set the model to evaluation mode\n",
|
| 242 |
+
" model.eval()\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" running_loss = 0.0\n",
|
| 245 |
+
" correct = 0\n",
|
| 246 |
+
" total = 0\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" with torch.no_grad():\n",
|
| 249 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 250 |
+
" # Move data to device\n",
|
| 251 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 252 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" # Forward pass\n",
|
| 255 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 256 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 257 |
+
" running_loss += loss.item()\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # Apply Softmax to get probabilities\n",
|
| 260 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # Pick the classes with highest probabilities\n",
|
| 263 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Accuracy calculation\n",
|
| 266 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 267 |
+
" total += y_batch.size(0)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" return avg_loss"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 282 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"input_dim = X_train.shape[1]\n",
|
| 285 |
+
"hidden_dim = 32\n",
|
| 286 |
+
"output_dim = 1\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"learning_rate = 0.001\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"criterion = nn.MSELoss()\n",
|
| 295 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 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 |
+
"# Run Training\n",
|
| 306 |
+
"num_epochs = 20\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"train_losses = []\n",
|
| 309 |
+
"val_losses = []\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"print('Starting Training...')\n",
|
| 313 |
+
"for epoch in range(num_epochs):\n",
|
| 314 |
+
" # Train one epoch\n",
|
| 315 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" # Validate\n",
|
| 318 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 319 |
+
"\n",
|
| 320 |
+
" train_losses.append(train_loss)\n",
|
| 321 |
+
" val_losses.append(val_loss)\n",
|
| 322 |
+
"\n",
|
| 323 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 324 |
+
" print(\n",
|
| 325 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 326 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 327 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 328 |
+
" )\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"print('Training Complete!')"
|
| 331 |
+
],
|
| 332 |
+
"execution_count": null,
|
| 333 |
+
"outputs": []
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"cell_type": "code",
|
| 337 |
+
"metadata": {},
|
| 338 |
+
"source": [
|
| 339 |
+
"# Task 1: Write your code here:\n",
|
| 340 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 343 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 344 |
+
"plt.title('Loss over Epochs')\n",
|
| 345 |
+
"plt.xlabel('Epoch')\n",
|
| 346 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 347 |
+
"plt.legend()\n",
|
| 348 |
+
"\n",
|
| 349 |
+
"plt.tight_layout()\n",
|
| 350 |
+
"plt.show()"
|
| 351 |
+
],
|
| 352 |
+
"execution_count": null,
|
| 353 |
+
"outputs": []
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"cell_type": "code",
|
| 357 |
+
"metadata": {},
|
| 358 |
+
"source": [
|
| 359 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
}
|
| 364 |
+
],
|
| 365 |
+
"metadata": {
|
| 366 |
+
"kernelspec": {
|
| 367 |
+
"display_name": "Python 3",
|
| 368 |
+
"name": "python3"
|
| 369 |
+
},
|
| 370 |
+
"language_info": {
|
| 371 |
+
"name": "python"
|
| 372 |
+
}
|
| 373 |
+
},
|
| 374 |
+
"nbformat": 4,
|
| 375 |
+
"nbformat_minor": 0
|
| 376 |
+
}
|
submissions_extracted/710/Q3.ipynb
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"\n",
|
| 29 |
+
"df = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"print(f\"Shape: {df.shape}\")\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()\n"
|
| 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_c=df.dropna(axis=1)\n",
|
| 72 |
+
"print(\"Missing values:\")\n",
|
| 73 |
+
"print(df_c.isnull().sum())"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# Task 2: Write your code here:\n",
|
| 83 |
+
"def check_duplicates(df):\n",
|
| 84 |
+
" duplicates = df.duplicated().sum()\n",
|
| 85 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 86 |
+
" if duplicates > 0:\n",
|
| 87 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 88 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 89 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 90 |
+
" else:\n",
|
| 91 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"check_duplicates(df_c)\n",
|
| 94 |
+
"df_c.drop_duplicates(inplace=True)"
|
| 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 |
+
"df_c.info()"
|
| 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 StandardScaler\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"print('data before scaling:\\n', df_c) #show before scaling\n",
|
| 117 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 118 |
+
"df_c = standard_scaler.fit_transform(df_c) # Apply fit_transform\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"print('\\nData after scaling:\\n', df_c) #show after scaling"
|
| 121 |
+
],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# Task 5: Write your code here:\n",
|
| 130 |
+
"import seaborn as sns\n",
|
| 131 |
+
"import matplotlib.pyplot as plt\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 134 |
+
" print(\"Target Distribution:\")\n",
|
| 135 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 136 |
+
" sns.countplot(x=df[target_column])\n",
|
| 137 |
+
" plt.title(\"Target Distribution\")\n",
|
| 138 |
+
" plt.show()\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"check_target_imbalance(df, \"Target\")"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# Task 1: Write your code here:\n",
|
| 150 |
+
"X = df.drop(\"Target\", axis=1)\n",
|
| 151 |
+
"y = df['Target']"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"\n",
|
| 161 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 162 |
+
"from sklearn.model_selection import KFold\n",
|
| 163 |
+
"from catboost import CatBoostClassifier\n",
|
| 164 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 165 |
+
"import numpy as np\n"
|
| 166 |
+
],
|
| 167 |
+
"execution_count": null,
|
| 168 |
+
"outputs": []
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"source": [
|
| 174 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"# Use previously generated random data (example: regression data)\n",
|
| 177 |
+
"X, y = X, y\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"# Define K-Fold Cross Validation\n",
|
| 180 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# Iterate through folds\n",
|
| 183 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 184 |
+
" # indexing for each fold\n",
|
| 185 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 186 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 187 |
+
" # print shapes\n",
|
| 188 |
+
" print(f\"Fold {fold}\")\n",
|
| 189 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 190 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 191 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 192 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 193 |
+
" print(\"-\" * 30)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"model = CatBoostClassifier()\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"model.fit(X_train, y_train)\n",
|
| 198 |
+
"print(\"Model trained!\")\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"y_pred = model.predict(X_test)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"acc = accuracy_score(y_test, y_pred)\n",
|
| 204 |
+
"f1 = f1_score(y_test, y_pred)\n",
|
| 205 |
+
"print('acc =',acc)\n",
|
| 206 |
+
"print('f1 =',f1)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"acc_scores = []\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"for train_idx, val_idx in kfold.split(X_train):\n",
|
| 214 |
+
" X_fold_train, X_fold_val = X_train[train_idx], X_test[val_idx]\n",
|
| 215 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_test.iloc[val_idx]\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # Train and predict\n",
|
| 218 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 219 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Calculate metrics\n",
|
| 222 |
+
" acc_scores.append(accuracy_score(y_test, y_pred))\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"acc_scores = np.array(acc_scores)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 229 |
+
"print(f\"MAE: ${acc_scores.mean():,.2f}\")"
|
| 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 |
+
"feature_cols==[]\n",
|
| 240 |
+
"for c in df_c.\n",
|
| 241 |
+
"feature_importance = pd.DataFrame({\n",
|
| 242 |
+
" 'feature': feature_cols,\n",
|
| 243 |
+
" 'importance': model.feature_importances_\n",
|
| 244 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 247 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 248 |
+
"plt.xlabel('Importance')\n",
|
| 249 |
+
"plt.title('Feature Importance')\n",
|
| 250 |
+
"plt.gca().invert_yaxis()\n",
|
| 251 |
+
"plt.show()"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
"# Task 2: Write your code here:\n",
|
| 261 |
+
"print(max(feature_importance))"
|
| 262 |
+
],
|
| 263 |
+
"execution_count": null,
|
| 264 |
+
"outputs": []
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"cell_type": "code",
|
| 268 |
+
"metadata": {},
|
| 269 |
+
"source": [
|
| 270 |
+
"# Task Bonus: Write your code here:"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
}
|
| 275 |
+
],
|
| 276 |
+
"metadata": {
|
| 277 |
+
"kernelspec": {
|
| 278 |
+
"display_name": "Python 3",
|
| 279 |
+
"name": "python3"
|
| 280 |
+
},
|
| 281 |
+
"language_info": {
|
| 282 |
+
"name": "python"
|
| 283 |
+
}
|
| 284 |
+
},
|
| 285 |
+
"nbformat": 4,
|
| 286 |
+
"nbformat_minor": 0
|
| 287 |
+
}
|
submissions_extracted/711/Q1.ipynb
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 16 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 17 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 18 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"import warnings\n",
|
| 21 |
+
"warnings.filterwarnings('ignore')\n",
|
| 22 |
+
"\n"
|
| 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 |
+
"\n",
|
| 33 |
+
"# Load the CSV file\n",
|
| 34 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"print(\"Path to dataset files:\", path)\n",
|
| 37 |
+
"del_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 38 |
+
"df_del = pd.read_csv(del_path)\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(f\"Shape: {df_del.shape}\")\n"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 2: Write your code here:\n",
|
| 50 |
+
"df_del.head()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 3: Write your code here:\n",
|
| 60 |
+
"df_del.info()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 4: Write your code here:\n",
|
| 70 |
+
"df_del.describe()"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 5: Write your code here:\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 82 |
+
"plt.hist(df_del['Delivery_Time'], bins=30, edgecolor='black')\n",
|
| 83 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 84 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 85 |
+
"plt.ylabel('Frequency')\n",
|
| 86 |
+
"plt.show()\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"#almost normaly distributed with some skewness"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# Task 1: Write your code here:\n",
|
| 98 |
+
"df_del=df_del.drop(['Order_ID'], axis=1)\n"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# Task 2: Write your code here:\n",
|
| 108 |
+
"print(\"Missing values:\")\n",
|
| 109 |
+
"print(df_del.isnull().sum())\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"# Analyze missing values\n",
|
| 112 |
+
"missing_percentage = (df_del.isnull().sum() / len(df_del)) * 100\n",
|
| 113 |
+
"missing_data = pd.DataFrame({\n",
|
| 114 |
+
" 'Column': missing_percentage.index,\n",
|
| 115 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 116 |
+
"})\n",
|
| 117 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 120 |
+
"missing_data.head(10)\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"\n"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"#all are less than 5 percent missing except \"Delivery_Time\" which is the target so we drop them\n",
|
| 133 |
+
"df_clean = df_del.dropna().copy()\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"\n"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 3: Write your code here:\n",
|
| 154 |
+
"def check_duplicates(df):\n",
|
| 155 |
+
" duplicates = df.duplicated().sum()\n",
|
| 156 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 157 |
+
" if duplicates > 0:\n",
|
| 158 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 159 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 160 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 161 |
+
" else:\n",
|
| 162 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 163 |
+
"check_duplicates(df_clean)"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"# Task 4: Write your code here:\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"#we have 4 catagorical features\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"def encode_categorical_columns(df):\n",
|
| 180 |
+
" categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 181 |
+
" print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 186 |
+
"for col in categorical_cols:\n",
|
| 187 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 188 |
+
" le = LabelEncoder()\n",
|
| 189 |
+
" df_clean[col] = le.fit_transform(df_clean[col])\n",
|
| 190 |
+
"df_clean\n"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# Task 5: Write your code here:\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 203 |
+
"scaler = StandardScaler()\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"df_clean[features] = scaler.fit_transform(df_clean[features])\n",
|
| 206 |
+
"df_clean.head()\n"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 6: Write your code here:\n",
|
| 216 |
+
"# Target distribution\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 219 |
+
"plt.hist(df_clean['Delivery_Time'], bins=30, edgecolor='black')\n",
|
| 220 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 221 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 222 |
+
"plt.ylabel('Frequency')\n",
|
| 223 |
+
"plt.show()"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task 1: Write your code here:\n",
|
| 233 |
+
"# Define features (X) and target (y)\n",
|
| 234 |
+
"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",
|
| 235 |
+
"X = df_clean[feature_cols]\n",
|
| 236 |
+
"y = df_clean['Delivery_Time']\n",
|
| 237 |
+
"\n"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 247 |
+
"from tqdm import tqdm\n",
|
| 248 |
+
"from sklearn.model_selection import KFold\n",
|
| 249 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 252 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 253 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 254 |
+
" losses = []\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
|
| 257 |
+
" y_hat = np.dot(X, theta)\n",
|
| 258 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 259 |
+
" theta -= learning_rate * gradient\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" loss = mean_absolute_error(y, y_hat)\n",
|
| 262 |
+
" losses.append(loss)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" return theta, losses\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"# Storage for linear regression results for each fold\n",
|
| 269 |
+
"lr_mae = []\n",
|
| 270 |
+
"n_splits=5\n",
|
| 271 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 272 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 275 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 278 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Train\n",
|
| 281 |
+
" theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" # Validate\n",
|
| 284 |
+
" y_pred = np.dot(X_test.values, theta)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" # Calculate evaluation metrics\n",
|
| 287 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" # Store results\n",
|
| 290 |
+
" lr_mae.append(mae)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 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 |
+
"\n"
|
| 305 |
+
],
|
| 306 |
+
"execution_count": null,
|
| 307 |
+
"outputs": []
|
| 308 |
+
},
|
| 309 |
+
{
|
| 310 |
+
"cell_type": "code",
|
| 311 |
+
"metadata": {},
|
| 312 |
+
"source": [
|
| 313 |
+
"# Task 2: Write your code here:"
|
| 314 |
+
],
|
| 315 |
+
"execution_count": null,
|
| 316 |
+
"outputs": []
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"cell_type": "code",
|
| 320 |
+
"metadata": {},
|
| 321 |
+
"source": [
|
| 322 |
+
"# Task Bonus: Write your code here:"
|
| 323 |
+
],
|
| 324 |
+
"execution_count": null,
|
| 325 |
+
"outputs": []
|
| 326 |
+
}
|
| 327 |
+
],
|
| 328 |
+
"metadata": {
|
| 329 |
+
"kernelspec": {
|
| 330 |
+
"display_name": "Python 3",
|
| 331 |
+
"name": "python3"
|
| 332 |
+
},
|
| 333 |
+
"language_info": {
|
| 334 |
+
"name": "python"
|
| 335 |
+
}
|
| 336 |
+
},
|
| 337 |
+
"nbformat": 4,
|
| 338 |
+
"nbformat_minor": 0
|
| 339 |
+
}
|