File size: 10,355 Bytes
0e43e41 9c7d102 0e43e41 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'c:\\\\Users\\\\nikhil\\\\OneDrive\\\\Desktop\\\\ML Projects\\\\ipp\\\\research'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%pwd"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"os.chdir(\"../\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'c:\\\\Users\\\\nikhil\\\\OneDrive\\\\Desktop\\\\ML Projects\\\\ipp'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%pwd"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"from dataclasses import dataclass\n",
"from pathlib import Path"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"@dataclass(frozen=True)\n",
"class ModelTrainingConfig:\n",
" root_dir : Path\n",
" model_path : Path\n",
" prepared_train_data : Path\n",
" prepared_test_data : Path\n",
" preprocessor_obj_file_path : Path"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"from insurancePP.constants import *\n",
"from insurancePP.utils.common import read_yaml, create_directories, save_object, load_object"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"class ConfigurationManager:\n",
" def __init__(self, config_filepath = CONFIG_FILE_PATH, params_filepath = PARAMS_FILE_PATH):\n",
" self.config = read_yaml(config_filepath)\n",
" self.params = read_yaml(params_filepath)\n",
"\n",
" create_directories([self.config.artifacts_root])\n",
"\n",
" def get_model_training_configuration(self) -> ModelTrainingConfig:\n",
" config = self.config.model_trainer\n",
" create_directories([config.root_dir])\n",
"\n",
" model_training_config = ModelTrainingConfig(\n",
" root_dir = config.root_dir,\n",
" model_path = config.model_path,\n",
" prepared_train_data = config.prepared_train_data,\n",
" prepared_test_data = config.prepared_test_data,\n",
" preprocessor_obj_file_path = config.preprocessor_obj_file_path\n",
" )\n",
"\n",
" return model_training_config\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"import pandas as pd\n",
"import numpy as np\n",
"from numpy import load\n",
"\n",
"from insurancePP.logging import logger\n",
"\n",
"from insurancePP.constants import *\n",
"from insurancePP.utils.common import read_yaml, create_directories, save_object, load_object, evaluate_models\n",
"\n",
"from dataclasses import dataclass\n",
"from catboost import CatBoostRegressor\n",
"from sklearn.ensemble import (\n",
" AdaBoostRegressor,\n",
" GradientBoostingRegressor,\n",
" RandomForestRegressor,\n",
")\n",
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.metrics import r2_score\n",
"from sklearn.neighbors import KNeighborsRegressor\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"from xgboost import XGBRegressor"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"class ModelTraining:\n",
" def __init__(self, config : ModelTrainingConfig):\n",
" self.config = config\n",
" \n",
"\n",
" def initiate_model_trainer(self):\n",
" try:\n",
" logger.info(\"loading the training and testing data\")\n",
" train_arr = load(self.config.prepared_train_data)\n",
" test_arr = load(self.config.prepared_test_data)\n",
"\n",
" logger.info(\"spliting the training and testing data\")\n",
" X_train, y_train, X_test, y_test = (\n",
" train_arr[:, :-1],\n",
" train_arr[:, -1],\n",
" test_arr[:, :-1],\n",
" test_arr[:, -1],\n",
" )\n",
"\n",
" models = {\n",
" \"Random Forest\": RandomForestRegressor(),\n",
" \"Decision Tree\": DecisionTreeRegressor(),\n",
" \"Gradient Boosting\": GradientBoostingRegressor(),\n",
" \"Linear Regression\": LinearRegression(),\n",
" \"XGBRegressor\": XGBRegressor(),\n",
" \"CatBoosting Regressor\": CatBoostRegressor(verbose=False),\n",
" \"AdaBoost Regressor\": AdaBoostRegressor(),\n",
" }\n",
"\n",
" params={\n",
" \"Decision Tree\": {\n",
" 'criterion':['squared_error', 'friedman_mse', 'absolute_error', 'poisson'],\n",
" },\n",
" \"Random Forest\":{\n",
" 'n_estimators': [8,16,32,64,128,256]\n",
" },\n",
" \"Gradient Boosting\":{\n",
" # 'learning_rate':[.1,.01,.05,.001],\n",
" 'n_estimators': [8,16,32,64,128,256]\n",
" },\n",
" \"Linear Regression\":{},\n",
" \"XGBRegressor\":{\n",
" 'learning_rate':[.1,.01,.05,.001],\n",
" 'n_estimators': [8,16,32,64,128,256]\n",
" },\n",
" \"CatBoosting Regressor\":{\n",
" 'depth': [6,8,10],\n",
" 'learning_rate': [0.01, 0.05, 0.1],\n",
" 'iterations': [30, 50, 100]\n",
" },\n",
" \"AdaBoost Regressor\":{\n",
" 'learning_rate':[.1,.01,0.5,.001],\n",
" 'n_estimators': [8,16,32,64,128,256]\n",
" }\n",
" }\n",
"\n",
" \n",
" model_report : dict = evaluate_models(X_train, y_train, X_test, y_test, models, params)\n",
" \n",
" performance_df = pd.DataFrame(list(zip(model_report.keys(), model_report.values())), columns=['Model Name', 'R2_Score']).sort_values(by=[\"R2_Score\"],ascending=False)\n",
" logger.info(f'Model Report: \\n {performance_df}')\n",
"\n",
" best_model_score = max(sorted(model_report.values()))\n",
" best_model_name = list(model_report.keys())[list(model_report.values()).index(best_model_score)]\n",
" best_model = models[best_model_name]\n",
"\n",
" # if best_model_score < 0.6:\n",
" # raise e\n",
" # logging.info(f\"Best model found on both training and testing dataset\")\n",
" \n",
" save_object(\n",
" file_path = Path(self.config.model_path),\n",
" obj = best_model\n",
" )\n",
"\n",
" predict = best_model.predict(X_test)\n",
" r2 = r2_score(y_test, predict)\n",
" \n",
"\n",
" except Exception as e:\n",
" raise e"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2024-02-25 21:29:34,497 : INFO : common : yaml file: config\\config.yaml loaded successfully]\n",
"[2024-02-25 21:29:34,501 : INFO : common : yaml file: params.yaml loaded successfully]\n",
"[2024-02-25 21:29:34,504 : INFO : common : directory artifacts created]\n",
"[2024-02-25 21:29:34,506 : INFO : common : directory artifacts/model_trainer created]\n",
"[2024-02-25 21:29:34,508 : INFO : 177425094 : loading the training and testing data]\n",
"[2024-02-25 21:29:34,513 : INFO : 177425094 : spliting the training and testing data]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2024-02-25 21:30:42,646 : INFO : 177425094 : Model Report: \n",
" Model Name R2_Score\n",
"5 CatBoosting Regressor 0.884958\n",
"2 Gradient Boosting 0.880510\n",
"6 AdaBoost Regressor 0.869562\n",
"4 XGBRegressor 0.868819\n",
"0 Random Forest 0.864245\n",
"3 Linear Regression 0.778228\n",
"1 Decision Tree 0.756036]\n",
"[2024-02-25 21:30:42,663 : INFO : common : Binary Object is stored]\n"
]
}
],
"source": [
"try:\n",
" config = ConfigurationManager()\n",
" data_training_config = config.get_model_training_configuration()\n",
" model_trainer = ModelTraining(config = data_training_config)\n",
" model_trainer.initiate_model_trainer()\n",
" \n",
"except Exception as e:\n",
" raise e"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "0.0.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|