SURESHBEEKHANI commited on
Commit
46d8269
·
verified ·
1 Parent(s): 7c3256e

Upload 29 files

Browse files
src/__init__.py ADDED
File without changes
src/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (170 Bytes). View file
 
src/__pycache__/exception.cpython-312.pyc ADDED
Binary file (1.61 kB). View file
 
src/__pycache__/logger.cpython-312.pyc ADDED
Binary file (919 Bytes). View file
 
src/__pycache__/model_evaluation.cpython-312.pyc ADDED
Binary file (2.78 kB). View file
 
src/__pycache__/utils.cpython-312.pyc ADDED
Binary file (8.85 kB). View file
 
src/components/__init__.py ADDED
File without changes
src/components/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (181 Bytes). View file
 
src/components/__pycache__/data_ingestion.cpython-312.pyc ADDED
Binary file (3.79 kB). View file
 
src/components/__pycache__/data_transformation.cpython-312.pyc ADDED
Binary file (5.52 kB). View file
 
src/components/__pycache__/model_tranier.cpython-312.pyc ADDED
Binary file (7.12 kB). View file
 
src/components/data_ingestion.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries and modules
2
+ import os # For file and directory operations
3
+ import sys # For system-specific parameters and functions
4
+ from src.exception import CustomException
5
+
6
+ from src.logger import logging # Adjusted to absolute import
7
+
8
+ import pandas as pd # For data manipulation and analysis
9
+
10
+ from sklearn.model_selection import train_test_split # For splitting data into training and testing sets
11
+ from dataclasses import dataclass # For creating data classes
12
+
13
+ #Import components for data transformation and model training
14
+ from src.components.data_transformation import DataTransformation ,DataTransformationConfig # Data transformation class
15
+ # Configuration for data transformation
16
+ from src.components.model_tranier import ModelTrainer, ModelTrainerConfig # type: ignore # Configuration for model training
17
+ # type: ignore # Model training class
18
+
19
+
20
+ # Initialize Data Ingestion Configuration
21
+ @dataclass
22
+ class DataIngestionConfig:
23
+ train_data_path: str = os.path.join('artifacts','train.csv')
24
+ test_data_path: str = os.path.join('artifacts','test.csv')
25
+ raw_data_path: str = os.path.join('artifacts','data.csv')
26
+
27
+ # Create a class for Data Ingestion
28
+ class DataIngestion:
29
+ def __init__(self):
30
+ # Initialize ingestion configuration
31
+ self.ingestion_config = DataIngestionConfig()
32
+
33
+ def initate_data_ingestion(self):
34
+ logging.info('Data ingestion method Started')
35
+ try:
36
+ df = pd.read_csv('notebook\data\heart.csv')
37
+ logging.info('Dataset read as pandas Dataframe')
38
+
39
+ os.makedirs(os.path.dirname(self.ingestion_config.raw_data_path),exist_ok=True)
40
+
41
+ df.to_csv(self.ingestion_config.raw_data_path,index=False)
42
+
43
+ logging.info('Train Test Split Initiated')
44
+ train_set, test_set = train_test_split(df, test_size=0.2, random_state=42)
45
+
46
+ train_set.to_csv(self.ingestion_config.train_data_path,index=False,header=True)
47
+ test_set.to_csv(self.ingestion_config.test_data_path,index=False,header=True)
48
+
49
+ logging.info('Ingestion of Data is completed')
50
+
51
+ return(
52
+ self.ingestion_config.train_data_path,
53
+ self.ingestion_config.test_data_path
54
+ )
55
+
56
+ except Exception as e:
57
+ logging.info('Exception occured at Data Ingestion stage')
58
+ raise CustomException(e, sys)
59
+
60
+ # Run Data ingestion
61
+ if __name__ == '__main__':
62
+ obj = DataIngestion()
63
+ train_data, test_data = obj.initate_data_ingestion()
64
+
65
+ # Create an instance of DataTransformation
66
+ data_transformation = DataTransformation()
67
+ train_arr, test_arr, _ = data_transformation.initate_data_transformation(train_data,test_data)
68
+
69
+ #Create an instance of ModelTrainer
70
+ model_trainer = ModelTrainer()
71
+ metrics = model_trainer.initiate_model_training(train_arr, test_arr)
72
+
src/components/data_transformation.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from dataclasses import dataclass
3
+ import numpy as np
4
+ import pandas as pd
5
+ from sklearn.compose import ColumnTransformer
6
+ from sklearn.impute import SimpleImputer
7
+ from sklearn.pipeline import Pipeline
8
+ from sklearn.preprocessing import OrdinalEncoder,StandardScaler
9
+
10
+ from ..exception import CustomException
11
+ from src.logger import logging
12
+ import os
13
+
14
+ from src.utils import save_object
15
+
16
+ @dataclass
17
+ class DataTransformationConfig:
18
+ preprocessor_obj_file_path = os.path.join('artifacts','preprocessor.pkl')
19
+
20
+ class DataTransformation:
21
+ def __init__(self):
22
+ self.data_transformation_config = DataTransformationConfig()
23
+
24
+ def get_data_transformation_object(self):
25
+ '''
26
+ This function is responsible for data transformation
27
+ '''
28
+ try:
29
+
30
+ # Define which columns should be ordinal-encoded and which should be scaled
31
+ categorical_cols = ['Sex', 'ChestPainType', 'RestingECG', 'ExerciseAngina', 'ST_Slope']
32
+ numerical_cols = ['Age', 'RestingBP', 'Cholesterol', 'FastingBS', 'MaxHR', 'Oldpeak']
33
+
34
+ # Define the custom ranking for each ordinal variable
35
+ Sex_categories = ['M','F']
36
+ CP_categories = ['ATA','NAP','ASY','TA']
37
+ RE_categories = ['Normal','ST','LVH']
38
+ EA_categories =['N','Y']
39
+ SS_categories = ['Up','Flat','Down']
40
+
41
+
42
+ # Numerical Pipeline
43
+ num_pipeline = Pipeline(
44
+ steps = [
45
+ ('imputer',SimpleImputer(strategy='median')),
46
+ ('scaler',StandardScaler())
47
+ ]
48
+ )
49
+
50
+ # Categorical Pipeline
51
+ cat_pipeline = Pipeline(
52
+ steps=[
53
+ ('imputer',SimpleImputer(strategy='most_frequent')),
54
+ ('ordinal_encoder',OrdinalEncoder(categories=[Sex_categories,CP_categories,RE_categories,EA_categories,SS_categories])),
55
+ ('scaler',StandardScaler())
56
+ ]
57
+ )
58
+
59
+ logging.info(f'Categorical Columns : {categorical_cols}')
60
+ logging.info(f'Numerical Columns : {numerical_cols}')
61
+
62
+ preprocessor = ColumnTransformer(
63
+ [
64
+ ('num_pipeline',num_pipeline,numerical_cols),
65
+ ('cat_pipeline',cat_pipeline,categorical_cols)
66
+ ]
67
+ )
68
+
69
+ return preprocessor
70
+
71
+ except Exception as e:
72
+ logging.info('Exception occured in Data Transformation Phase')
73
+ raise CustomException(e,sys)
74
+
75
+ def initate_data_transformation(self,train_path,test_path):
76
+
77
+ try:
78
+ # Reading train and test data
79
+ train_df = pd.read_csv(train_path)
80
+ test_df = pd.read_csv(test_path)
81
+
82
+ logging.info('Read train and test data completed')
83
+ logging.info(f'Train Dataframe Head : \n{train_df.head().to_string()}')
84
+ logging.info(f'Test Dataframe Head : \n{test_df.head().to_string()}')
85
+
86
+ logging.info('Obtaining preprocessing object')
87
+
88
+ preprocessing_obj = self.get_data_transformation_object()
89
+
90
+ target_column_name = 'HeartDisease'
91
+ drop_columns = [target_column_name]
92
+
93
+ input_feature_train_df = train_df.drop(columns=drop_columns,axis=1)
94
+ target_feature_train_df=train_df[target_column_name]
95
+
96
+ input_feature_test_df=test_df.drop(columns=drop_columns,axis=1)
97
+ target_feature_test_df=test_df[target_column_name]
98
+
99
+ logging.info("Applying preprocessing object on training and testing datasets.")
100
+
101
+ input_feature_train_arr=preprocessing_obj.fit_transform(input_feature_train_df)
102
+ input_feature_test_arr=preprocessing_obj.transform(input_feature_test_df)
103
+
104
+ train_arr = np.c_[input_feature_train_arr, np.array(target_feature_train_df)]
105
+ test_arr = np.c_[input_feature_test_arr, np.array(target_feature_test_df)]
106
+
107
+ save_object(
108
+
109
+ file_path=self.data_transformation_config.preprocessor_obj_file_path,
110
+ obj=preprocessing_obj
111
+
112
+ )
113
+ logging.info('Preprocessor pickle file saved')
114
+
115
+ return (
116
+ train_arr,
117
+ test_arr,
118
+ self.data_transformation_config.preprocessor_obj_file_path,
119
+ )
120
+
121
+ except Exception as e:
122
+ logging.info('Exception occured in initiate_data_transformation function')
123
+ raise CustomException(e,sys)
src/components/model_tranier.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from dataclasses import dataclass
4
+
5
+ # Importing necessary libraries for machine learning models and evaluation
6
+ from sklearn.linear_model import LogisticRegression # type: ignore
7
+ from sklearn.tree import DecisionTreeClassifier # type: ignore
8
+ from sklearn.ensemble import (RandomForestClassifier, AdaBoostClassifier, VotingClassifier) # type: ignore
9
+ from sklearn.neighbors import KNeighborsClassifier # type: ignore
10
+ from xgboost import XGBClassifier # type: ignore
11
+ from catboost import CatBoostClassifier # type: ignore
12
+ from sklearn.model_selection import (GridSearchCV, RandomizedSearchCV) # type: ignore
13
+ import pandas as pd # type: ignore
14
+ import matplotlib.pyplot as plt # type: ignore
15
+ import numpy as np
16
+
17
+ from ..exception import CustomException
18
+ from src.logger import logging
19
+ from src.utils import save_object, evaluate_models, model_metrics, print_evaluated_results
20
+
21
+ @dataclass
22
+ class ModelTrainerConfig:
23
+ """Configuration for Model Trainer."""
24
+ trained_model_file_path: str = os.path.join('artifacts', 'model.pkl')
25
+
26
+ class ModelTrainer:
27
+ """Class for training machine learning models."""
28
+
29
+ def __init__(self):
30
+ self.model_trainer_config = ModelTrainerConfig()
31
+
32
+ def initiate_model_training(self, train_array: np.ndarray, test_array: np.ndarray):
33
+ """Initiates model training process."""
34
+ try:
35
+ logging.info('Splitting dependent and independent variables from train and test data')
36
+ x_train, y_train, x_test, y_test = (
37
+ train_array[:, :-1],
38
+ train_array[:, -1],
39
+ test_array[:, :-1],
40
+ test_array[:, -1]
41
+ )
42
+
43
+ models = {
44
+ "Logistic Regression": LogisticRegression(),
45
+ "K-Neighbors Classifier": KNeighborsClassifier(),
46
+ "Decision Tree": DecisionTreeClassifier(),
47
+ "Random Forest Classifier": RandomForestClassifier(),
48
+ "XGB Classifier": XGBClassifier(),
49
+ "CatBoost Classifier": CatBoostClassifier(verbose=False),
50
+ "AdaBoost Classifier": AdaBoostClassifier(),
51
+ }
52
+
53
+ model_report = evaluate_models(x_train, y_train, x_test, y_test, models)
54
+ logging.info(f'Model Report: {model_report}')
55
+
56
+ best_model_name, best_model_score = self.get_best_model(model_report)
57
+
58
+ # Check if the best model score is satisfactory
59
+ if best_model_score < 0.6:
60
+
61
+ logging.info('Best model has R2 Score less than 60%')
62
+
63
+ print(f'Best Model Found: Model Name: {best_model_name}, R2 Score: {best_model_score}')
64
+ print('\n====================================================================================\n')
65
+ logging.info(f'Best Model Found: Model Name: {best_model_name}, R2 Score: {best_model_score}')
66
+
67
+ # Hyperparameter tuning for CatBoost
68
+ logging.info('Hyperparameter tuning started for CatBoost')
69
+ cbr = CatBoostClassifier(verbose=False)
70
+ param_dist = {
71
+ 'depth': [4, 5, 6, 7, 8, 9, 10],
72
+ 'learning_rate': [0.01, 0.02, 0.03, 0.04],
73
+ 'iterations': [300, 400, 500, 600]
74
+ }
75
+ rscv = RandomizedSearchCV(cbr, param_dist, scoring='r2', cv=5, n_jobs=-1)
76
+ rscv.fit(x_train, y_train)
77
+
78
+ # Print the tuned parameters and score
79
+ print(f'Best CatBoost Parameters: {rscv.best_params_}')
80
+ print(f'Best CatBoost Score: {rscv.best_score_}')
81
+ print('\n====================================================================================\n')
82
+
83
+ best_cbr = rscv.best_estimator_
84
+ logging.info('Hyperparameter tuning complete for CatBoost')
85
+
86
+ # Hyperparameter tuning for KNN
87
+ logging.info('Hyperparameter tuning started for KNN')
88
+ knn = KNeighborsClassifier()
89
+ param_grid = {'n_neighbors': list(range(2, 31))}
90
+ grid = GridSearchCV(knn, param_grid, cv=5, scoring='r2', n_jobs=-1)
91
+ grid.fit(x_train, y_train)
92
+
93
+ # Print the tuned parameters and score
94
+ print(f'Best KNN Parameters: {grid.best_params_}')
95
+ print(f'Best KNN Score: {grid.best_score_}')
96
+ print('\n====================================================================================\n')
97
+
98
+ best_knn = grid.best_estimator_
99
+ logging.info('Hyperparameter tuning complete for KNN')
100
+
101
+ # Create and train Voting Classifier
102
+ logging.info('Voting Classifier training started')
103
+ voting_classifier = VotingClassifier(
104
+ estimators=[('catboost', best_cbr), ('xgb', XGBClassifier()), ('knn', best_knn)],
105
+ weights=[3, 2, 1]
106
+ )
107
+ voting_classifier.fit(x_train, y_train)
108
+
109
+ print('Final Model Evaluation:\n')
110
+ print_evaluated_results(x_train, y_train, x_test, y_test, voting_classifier)
111
+ logging.info('Voting Classifier training completed')
112
+
113
+ # Save the trained model
114
+ save_object(file_path=self.model_trainer_config.trained_model_file_path, obj=voting_classifier)
115
+ logging.info('Model pickle file saved')
116
+
117
+ # Evaluate final model on test data
118
+ y_test_pred = voting_classifier.predict(x_test)
119
+ mae, rmse, r2 = model_metrics(y_test, y_test_pred)
120
+ logging.info(f'Test MAE: {mae}')
121
+ logging.info(f'Test RMSE: {rmse}')
122
+ logging.info(f'Test R2 Score: {r2}')
123
+ logging.info('Final Model Training Completed')
124
+
125
+ return mae, rmse, r2
126
+
127
+ except Exception as e:
128
+ logging.info('Exception occurred during model training')
129
+ raise CustomException(e, sys)
130
+
131
+ def get_best_model(self, model_report: dict):
132
+ """Get the best model based on the evaluation report."""
133
+ best_model_name = max(model_report, key=model_report.get)
134
+ best_model_score = model_report[best_model_name]
135
+ return best_model_name, best_model_score
src/exception.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/exception.py
2
+ import sys
3
+ from src.logger import logging
4
+
5
+ class CustomException(Exception):
6
+ def __init__(self, error_message: Exception, error_detail: sys):
7
+ super().__init__(error_message)
8
+ self.error_message = CustomException.get_detailed_error_message(error_message, error_detail)
9
+
10
+ @staticmethod
11
+ def get_detailed_error_message(error: Exception, error_detail: sys):
12
+ _, _, exc_tb = error_detail.exc_info()
13
+ file_name = exc_tb.tb_frame.f_code.co_filename
14
+ line_number = exc_tb.tb_lineno
15
+ error_message = f"Error occurred in script: {file_name} at line {line_number}: {str(error)}"
16
+ return error_message
17
+
18
+ def __str__(self):
19
+ return self.error_message
src/logger.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from datetime import datetime
4
+
5
+ LOG_FILE=f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log"
6
+ logs_path=os.path.join(os.getcwd(),"logs",LOG_FILE)
7
+ os.makedirs(logs_path,exist_ok=True)
8
+
9
+ LOG_FILE_PATH=os.path.join(logs_path,LOG_FILE)
10
+
11
+ logging.basicConfig(
12
+ filename=LOG_FILE_PATH,
13
+ format="[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s",
14
+ level=logging.INFO
15
+ )
src/pipelines/__init__.py ADDED
File without changes
src/pipelines/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (180 Bytes). View file
 
src/pipelines/__pycache__/prediction_pipeline.cpython-312.pyc ADDED
Binary file (4.91 kB). View file
 
src/pipelines/prediction_pipeline.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import pandas as pd
3
+ from src.exception import CustomException
4
+ from src.logger import logging
5
+ from src.utils import load_object
6
+
7
+ class PredictPipeline:
8
+ def __init__(self):
9
+ pass # Initialize the PredictPipeline class
10
+
11
+ def predict(self, features):
12
+ """
13
+ Predict the target variable using the pre-trained model.
14
+
15
+ Parameters:
16
+ features (DataFrame): DataFrame containing input features for prediction.
17
+
18
+ Returns:
19
+ pred: Prediction results from the model.
20
+ """
21
+ try:
22
+ # Load preprocessor and model from the specified paths
23
+ preprocessor_path = 'artifacts/preprocessor.pkl'
24
+ model_path = 'artifacts/model.pkl'
25
+ preprocessor = load_object(file_path=preprocessor_path)
26
+ model = load_object(file_path=model_path)
27
+
28
+ # Scale the input features using the loaded preprocessor
29
+ data_scaled = preprocessor.transform(features)
30
+
31
+ # Make predictions using the scaled data
32
+ pred = model.predict(data_scaled)
33
+ return pred
34
+ except Exception as e:
35
+ # Log the exception and raise a custom exception
36
+ logging.info('Exception occurred in prediction pipeline')
37
+ raise CustomException(e, sys)
38
+
39
+ class CustomData:
40
+ def __init__(self,
41
+ age: int,
42
+ sex: str,
43
+ chest_pain_type: str,
44
+ resting_bp: float,
45
+ cholesterol: float,
46
+ fasting_bs: int,
47
+ resting_ecg: str, # Added resting ECG
48
+ max_hr: float,
49
+ exercise_angina: str,
50
+ oldpeak: float,
51
+ st_slope: str):
52
+ """
53
+ Initialize custom data for prediction.
54
+
55
+ Parameters:
56
+ age (float): Age of the patient.
57
+ sex (str): Gender of the patient (M/F).
58
+ chest_pain_type (str): Type of chest pain (ATA/NAP/ASY).
59
+ resting_bp (float): Resting blood pressure.
60
+ cholesterol (float): Cholesterol level.
61
+ fasting_bs (int): Fasting blood sugar level (0 or 1).
62
+ resting_ecg (str): Resting ECG results (Normal/ST).
63
+ max_hr (float): Maximum heart rate achieved.
64
+ oldpeak (float): ST depression induced by exercise relative to rest.
65
+ exercise_angina (str): Whether the patient experiences angina during exercise (Y/N).
66
+ st_slope (str): The slope of the ST segment (Up/Flat/Down).
67
+ """
68
+ if age is None or resting_bp is None or cholesterol is None or max_hr is None or oldpeak is None:
69
+ raise ValueError("Numeric fields cannot be None")
70
+
71
+ self.age = age
72
+ self.sex = sex
73
+ self.chest_pain_type = chest_pain_type
74
+ self.resting_bp = resting_bp
75
+ self.cholesterol = cholesterol
76
+ self.fasting_bs = fasting_bs
77
+ self.resting_ecg = resting_ecg
78
+ self.max_hr = max_hr
79
+ self.oldpeak = oldpeak
80
+ self.exercise_angina = exercise_angina
81
+ self.st_slope = st_slope
82
+
83
+ def get_data_as_dataframe(self):
84
+ """
85
+ Convert the input data into a pandas DataFrame.
86
+
87
+ Returns:
88
+ DataFrame: DataFrame containing the input features.
89
+ """
90
+ try:
91
+ # Create a dictionary with the input data
92
+ custom_data_input_dict = {
93
+ 'Age': [self.age],
94
+ 'Sex': [self.sex],
95
+ 'ChestPainType': [self.chest_pain_type],
96
+ 'RestingBP': [self.resting_bp],
97
+ 'Cholesterol': [self.cholesterol],
98
+ 'FastingBS': [self.fasting_bs],
99
+ 'RestingECG': [self.resting_ecg],
100
+ 'MaxHR': [self.max_hr],
101
+ 'Oldpeak': [self.oldpeak],
102
+ 'ExerciseAngina': [self.exercise_angina],
103
+ 'ST_Slope': [self.st_slope]
104
+ }
105
+ # Convert the dictionary to a DataFrame
106
+ df = pd.DataFrame(custom_data_input_dict)
107
+ logging.info('Dataframe gathered successfully')
108
+ logging.info(f"DataFrame contents: {df}") # Log the DataFrame contents
109
+ return df
110
+ except Exception as e:
111
+ # Log any exceptions that occur during DataFrame creation
112
+ logging.info('Exception occurred in getting dataframe')
113
+ raise CustomException(e, sys)
src/pipelines/training_pipeline.py ADDED
File without changes
src/utils.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import numpy as np
4
+ import pandas as pd
5
+ import dill
6
+ from sklearn.metrics import (
7
+ r2_score,
8
+ mean_absolute_error,
9
+ mean_squared_error,
10
+ confusion_matrix,
11
+ accuracy_score,
12
+ precision_score,
13
+ recall_score,
14
+ f1_score
15
+ )
16
+
17
+ from src.exception import CustomException
18
+ from src.logger import logging
19
+
20
+ def save_object(file_path: str, obj: object) -> None:
21
+ """Saves an object to a specified file path using dill.
22
+
23
+ Args:
24
+ file_path (str): The path where the object will be saved.
25
+ obj (object): The object to be saved.
26
+
27
+ Raises:
28
+ CustomException: If an error occurs during saving.
29
+ """
30
+ try:
31
+ dir_path = os.path.dirname(file_path)
32
+ os.makedirs(dir_path, exist_ok=True)
33
+
34
+ with open(file_path, "wb") as file_obj:
35
+ dill.dump(obj, file_obj)
36
+
37
+ except Exception as e:
38
+ raise CustomException(e, sys)
39
+
40
+ def evaluate_models(xtrain: np.ndarray, ytrain: np.ndarray, xtest: np.ndarray, ytest: np.ndarray, models: dict) -> dict:
41
+ """Evaluates multiple models and returns their test scores.
42
+
43
+ Args:
44
+ xtrain (np.ndarray): Training features.
45
+ ytrain (np.ndarray): Training labels.
46
+ xtest (np.ndarray): Testing features.
47
+ ytest (np.ndarray): Testing labels.
48
+ models (dict): A dictionary of models to evaluate.
49
+
50
+ Returns:
51
+ dict: A dictionary containing model names and their corresponding test scores.
52
+
53
+ Raises:
54
+ CustomException: If an error occurs during evaluation.
55
+ """
56
+ try:
57
+ report = {}
58
+ for model_name, model in models.items():
59
+ # Train model
60
+ model.fit(xtrain, ytrain)
61
+
62
+ # Predict Training data
63
+ y_train_pred = model.predict(xtrain)
64
+
65
+ # Predict Testing data
66
+ y_test_pred = model.predict(xtest)
67
+
68
+ # Get R2 scores for train and test data
69
+ test_model_score = r2_score(ytest, y_test_pred)
70
+ report[model_name] = test_model_score
71
+
72
+ return report
73
+
74
+ except Exception as e:
75
+ logging.info('Exception occurred during model evaluation')
76
+ raise CustomException(e, sys)
77
+
78
+ def model_metrics(true: np.ndarray, predicted: np.ndarray) -> tuple:
79
+ """Calculates regression metrics: MAE, RMSE, and R2 Score.
80
+
81
+ Args:
82
+ true (np.ndarray): True values.
83
+ predicted (np.ndarray): Predicted values.
84
+
85
+ Returns:
86
+ tuple: A tuple containing MAE, RMSE, and R2 Score.
87
+
88
+ Raises:
89
+ CustomException: If an error occurs during metrics calculation.
90
+ """
91
+ try:
92
+ mae = mean_absolute_error(true, predicted)
93
+ mse = mean_squared_error(true, predicted)
94
+ rmse = np.sqrt(mse)
95
+ r2_square = r2_score(true, predicted)
96
+ return mae, rmse, r2_square
97
+ except Exception as e:
98
+ logging.info('Exception occurred while evaluating regression metrics')
99
+ raise CustomException(e, sys)
100
+
101
+ def classification_metrics(true: np.ndarray, predicted: np.ndarray) -> tuple:
102
+ """Calculates classification metrics: accuracy, precision, recall, and F1 score.
103
+
104
+ Args:
105
+ true (np.ndarray): True labels.
106
+ predicted (np.ndarray): Predicted labels.
107
+
108
+ Returns:
109
+ tuple: A tuple containing accuracy, precision, recall, F1 score, and confusion matrix.
110
+
111
+ Raises:
112
+ CustomException: If an error occurs during metrics calculation.
113
+ """
114
+ try:
115
+ accuracy = accuracy_score(true, predicted)
116
+ precision = precision_score(true, predicted, average='weighted') # Use appropriate averaging method
117
+ recall = recall_score(true, predicted, average='weighted') # Use appropriate averaging method
118
+ f1 = f1_score(true, predicted, average='weighted') # Use appropriate averaging method
119
+ cm = confusion_matrix(true, predicted)
120
+
121
+ return accuracy, precision, recall, f1, cm
122
+ except Exception as e:
123
+ logging.info('Exception occurred while evaluating classification metrics')
124
+ raise CustomException(e, sys)
125
+
126
+ def print_evaluated_results(xtrain: np.ndarray, ytrain: np.ndarray, xtest: np.ndarray, ytest: np.ndarray, model) -> None:
127
+ """Prints evaluation results for both training and testing datasets.
128
+
129
+ Args:
130
+ xtrain (np.ndarray): Training features.
131
+ ytrain (np.ndarray): Training labels.
132
+ xtest (np.ndarray): Testing features.
133
+ ytest (np.ndarray): Testing labels.
134
+ model: Trained model to evaluate.
135
+
136
+ Raises:
137
+ CustomException: If an error occurs during printing of evaluated results.
138
+ """
139
+ try:
140
+ ytrain_pred = model.predict(xtrain)
141
+ ytest_pred = model.predict(xtest)
142
+
143
+ # Evaluate Train and Test dataset for regression metrics
144
+ model_train_mae, model_train_rmse, model_train_r2 = model_metrics(ytrain, ytrain_pred)
145
+ model_test_mae, model_test_rmse, model_test_r2 = model_metrics(ytest, ytest_pred)
146
+
147
+ # Evaluate classification metrics
148
+ accuracy, precision, recall, f1, cm = classification_metrics(ytest, ytest_pred)
149
+
150
+ # Printing regression results
151
+ print('Model performance for Training set')
152
+ print("- Root Mean Squared Error: {:.4f}".format(model_train_rmse))
153
+ print("- Mean Absolute Error: {:.4f}".format(model_train_mae))
154
+ print("- R2 Score: {:.4f}".format(model_train_r2))
155
+
156
+ print('----------------------------------')
157
+
158
+ print('Model performance for Test set')
159
+ print("- Root Mean Squared Error: {:.4f}".format(model_test_rmse))
160
+ print("- Mean Absolute Error: {:.4f}".format(model_test_mae))
161
+ print("- R2 Score: {:.4f}".format(model_test_r2))
162
+
163
+ # Printing classification results
164
+ print('----------------------------------')
165
+ print('Classification Metrics for Test set')
166
+ print("- Accuracy: {:.4f}".format(accuracy))
167
+ print("- Precision: {:.4f}".format(precision))
168
+ print("- Recall: {:.4f}".format(recall))
169
+ print("- F1 Score: {:.4f}".format(f1))
170
+ print("Confusion Matrix:\n", cm)
171
+
172
+ except Exception as e:
173
+ logging.info('Exception occurred during printing of evaluated results')
174
+ raise CustomException(e, sys)
175
+
176
+ def load_object(file_path: str) -> object:
177
+ """Loads an object from a specified file path using dill.
178
+
179
+ Args:
180
+ file_path (str): The path from where the object will be loaded.
181
+
182
+ Returns:
183
+ object: The loaded object.
184
+
185
+ Raises:
186
+ CustomException: If an error occurs during loading.
187
+ """
188
+ try:
189
+ with open(file_path, 'rb') as file_obj:
190
+ return dill.load(file_obj)
191
+ except Exception as e:
192
+ logging.info('Exception occurred in load_object function')
193
+ raise CustomException(e, sys)