|
| 1 | +import sys |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from sklearn.ensemble import ( |
| 5 | + AdaBoostClassifier, |
| 6 | + GradientBoostingClassifier, |
| 7 | + RandomForestClassifier, |
| 8 | +) |
| 9 | +from sklearn.linear_model import LogisticRegression |
| 10 | +from sklearn.tree import DecisionTreeClassifier |
| 11 | + |
| 12 | +from network_security.entity.artifact_entity import ( |
| 13 | + DataTransformationArtifact, |
| 14 | + ModelTrainerArtifact, |
| 15 | +) |
| 16 | +from network_security.entity.config_entity import ModelTrainerConfig |
| 17 | +from network_security.exception.exception import NetworkSecurityException |
| 18 | +from network_security.logging.logger import logging |
| 19 | +from network_security.utils.main_utils.utils import ( |
| 20 | + load_numpy_array_data, |
| 21 | + load_object, |
| 22 | + save_object, |
| 23 | +) |
| 24 | +from network_security.utils.ml_utils.evaluation.evaluation import evaluate_models |
| 25 | +from network_security.utils.ml_utils.metric.classification_metric import ( |
| 26 | + get_classification_score, |
| 27 | +) |
| 28 | +from network_security.utils.ml_utils.model.estimator import NetworkModel |
| 29 | + |
| 30 | + |
| 31 | +class ModelTrainer: |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + model_trainer_config: ModelTrainerConfig, |
| 35 | + data_transformation_artifact: DataTransformationArtifact, |
| 36 | + ) -> None: |
| 37 | + try: |
| 38 | + self.model_trainer_config = model_trainer_config |
| 39 | + self.data_transformation_artifact = data_transformation_artifact |
| 40 | + except Exception as e: |
| 41 | + raise NetworkSecurityException(e, sys) |
| 42 | + |
| 43 | + def train_model( |
| 44 | + self, |
| 45 | + X_train: object, |
| 46 | + y_train: object, |
| 47 | + X_test: object, |
| 48 | + y_test: object, |
| 49 | + ) -> ModelTrainerArtifact: |
| 50 | + models = { |
| 51 | + "Random Forest": RandomForestClassifier(verbose=1), |
| 52 | + "Decision Tree": DecisionTreeClassifier(), |
| 53 | + "Gradient Boosting": GradientBoostingClassifier(verbose=1), |
| 54 | + "Logistic Regression": LogisticRegression(verbose=1), |
| 55 | + "AdaBoost": AdaBoostClassifier(), |
| 56 | + } |
| 57 | + params = { |
| 58 | + "Decision Tree": { |
| 59 | + "criterion": ["gini", "entropy", "log_loss"], |
| 60 | + "splitter": ["best", "random"], |
| 61 | + "max_features": ["sqrt", "log2"], |
| 62 | + }, |
| 63 | + "Random Forest": { |
| 64 | + "criterion": ["gini", "entropy", "log_loss"], |
| 65 | + "max_features": ["sqrt", "log2", None], |
| 66 | + "n_estimators": [8, 16, 32, 128, 256], |
| 67 | + }, |
| 68 | + "Gradient Boosting": { |
| 69 | + "loss": ["log_loss", "exponential"], |
| 70 | + "learning_rate": [0.1, 0.01, 0.05, 0.001], |
| 71 | + "subsample": [0.6, 0.7, 0.75, 0.85, 0.9], |
| 72 | + "criterion": ["squared_error", "friedman_mse"], |
| 73 | + "max_features": ["auto", "sqrt", "log2"], |
| 74 | + "n_estimators": [8, 16, 32, 64, 128, 256], |
| 75 | + }, |
| 76 | + "Logistic Regression": {}, |
| 77 | + "AdaBoost": { |
| 78 | + "learning_rate": [0.1, 0.01, 0.001], |
| 79 | + "n_estimators": [8, 16, 32, 64, 128, 256], |
| 80 | + }, |
| 81 | + } |
| 82 | + model_report: dict = evaluate_models( |
| 83 | + X_train=X_train, |
| 84 | + y_train=y_train, |
| 85 | + X_test=X_test, |
| 86 | + y_test=y_test, |
| 87 | + models=models, |
| 88 | + param=params, |
| 89 | + ) |
| 90 | + |
| 91 | + ## To get best model score from dict |
| 92 | + best_model_score = max(sorted(model_report.values())) |
| 93 | + |
| 94 | + ## To get best model name from dict |
| 95 | + best_model_name = list(model_report.keys())[ |
| 96 | + list(model_report.values()).index(best_model_score) |
| 97 | + ] |
| 98 | + best_model = models[best_model_name] |
| 99 | + y_train_pred = best_model.predict(X_train) |
| 100 | + |
| 101 | + classification_train_metric = get_classification_score( |
| 102 | + y_true=y_train, |
| 103 | + y_pred=y_train_pred, |
| 104 | + ) |
| 105 | + |
| 106 | + y_test_pred = best_model.predict(X_test) |
| 107 | + classification_test_metric = get_classification_score( |
| 108 | + y_true=y_test, |
| 109 | + y_pred=y_test_pred, |
| 110 | + ) |
| 111 | + |
| 112 | + preprocessor = load_object( |
| 113 | + file_path=self.data_transformation_artifact.transformed_object_file_path, |
| 114 | + ) |
| 115 | + model_dir_path = Path(self.model_trainer_config.trained_model_file_path).parent |
| 116 | + model_dir_path.mkdir(parents=True, exist_ok=True) |
| 117 | + |
| 118 | + network_model = NetworkModel(preprocessor=preprocessor, model=best_model) |
| 119 | + save_object(self.model_trainer_config.trained_model_file_path, obj=NetworkModel) |
| 120 | + |
| 121 | + ## Model pusher |
| 122 | + save_object("final_model/model.pkl", best_model) |
| 123 | + |
| 124 | + ## Model Trainer Artifact |
| 125 | + model_trainer_artifact = ModelTrainerArtifact( |
| 126 | + trained_model_file_path=self.model_trainer_config.trained_model_file_path, |
| 127 | + train_metric_artifact=classification_train_metric, |
| 128 | + test_metric_artifact=classification_test_metric, |
| 129 | + ) |
| 130 | + logging.info(f"Model trainer artifact: {model_trainer_artifact}") |
| 131 | + return model_trainer_artifact |
| 132 | + |
| 133 | + def initiate_model_trainer(self) -> ModelTrainerArtifact: |
| 134 | + try: |
| 135 | + train_file_path = ( |
| 136 | + self.data_transformation_artifact.transformed_train_file_path |
| 137 | + ) |
| 138 | + test_file_path = ( |
| 139 | + self.data_transformation_artifact.transformed_test_file_path |
| 140 | + ) |
| 141 | + |
| 142 | + # Loading training array and testing array |
| 143 | + train_arr = load_numpy_array_data(train_file_path) |
| 144 | + test_arr = load_numpy_array_data(test_file_path) |
| 145 | + |
| 146 | + x_train, y_train, x_test, y_test = ( |
| 147 | + train_arr[:, :-1], |
| 148 | + train_arr[:, -1], |
| 149 | + test_arr[:, :-1], |
| 150 | + test_arr[:, -1], |
| 151 | + ) |
| 152 | + |
| 153 | + model_trainer_artifact = self.train_model(x_train, y_train, x_test, y_test) |
| 154 | + return model_trainer_artifact |
| 155 | + |
| 156 | + except Exception as e: |
| 157 | + raise NetworkSecurityException(e, sys) |
0 commit comments