models_final_fitting.py 7.48 KB
Newer Older
Joaquin Torres's avatar
Joaquin Torres committed
1 2 3 4 5 6
# Fitting Final Models
# Author: Joaquín Torres Bravo
"""
    Script to fit and save chosen models to be later used in SHAP
"""

7 8 9 10
# Libraries
# --------------------------------------------------------------------------------------------------------
import pandas as pd
import numpy as np
Joaquin Torres's avatar
Joaquin Torres committed
11 12 13
import shap # Explainability
import pickle # Loading/saving models
# Models
14 15 16 17 18 19
from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier, BaggingClassifier, AdaBoostClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.linear_model import  LogisticRegression
from sklearn.tree import DecisionTreeClassifier
Joaquin Torres's avatar
Joaquin Torres committed
20
import ast # String to dictionary
21 22 23 24 25 26
# --------------------------------------------------------------------------------------------------------

# Reading training data
# --------------------------------------------------------------------------------------------------------
def read_training_data(attribute_names):
    # Load ORIGINAL training data
Joaquin Torres's avatar
Joaquin Torres committed
27 28 29 30
    X_train_pre = np.load('../02-training_data_generation/results/pre/X_train_pre.npy', allow_pickle=True)
    y_train_pre = np.load('../02-training_data_generation/results/pre/y_train_pre.npy', allow_pickle=True)
    X_train_post = np.load('../02-training_data_generation/results/post/X_train_post.npy', allow_pickle=True)
    y_train_post = np.load('../02-training_data_generation/results/post/y_train_post.npy', allow_pickle=True)
31 32

    # Load oversampled training data
Joaquin Torres's avatar
Joaquin Torres committed
33 34 35 36
    X_train_over_pre = np.load('../02-training_data_generation/results/pre/X_train_over_pre.npy', allow_pickle=True)
    y_train_over_pre = np.load('../02-training_data_generation/results/pre/y_train_over_pre.npy', allow_pickle=True)
    X_train_over_post = np.load('../02-training_data_generation/results/post/X_train_over_post.npy', allow_pickle=True)
    y_train_over_post = np.load('../02-training_data_generation/results/post/y_train_over_post.npy', allow_pickle=True)
37 38

    # Load undersampled training data
Joaquin Torres's avatar
Joaquin Torres committed
39 40 41 42
    X_train_under_pre = np.load('../02-training_data_generation/results/pre/X_train_under_pre.npy', allow_pickle=True)
    y_train_under_pre = np.load('../02-training_data_generation/results/pre/y_train_under_pre.npy', allow_pickle=True)
    X_train_under_post = np.load('../02-training_data_generation/results/post/X_train_under_post.npy', allow_pickle=True)
    y_train_under_post = np.load('../02-training_data_generation/results/post/y_train_under_post.npy', allow_pickle=True)
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

    # Type conversion needed    
    data_dic = {
        "X_train_pre": pd.DataFrame(X_train_pre, columns=attribute_names).convert_dtypes(),
        "y_train_pre": y_train_pre,
        "X_train_post": pd.DataFrame(X_train_post, columns=attribute_names).convert_dtypes(),
        "y_train_post": y_train_post,
        "X_train_over_pre": pd.DataFrame(X_train_over_pre, columns=attribute_names).convert_dtypes(),
        "y_train_over_pre": y_train_over_pre,
        "X_train_over_post": pd.DataFrame(X_train_over_post, columns=attribute_names).convert_dtypes(),
        "y_train_over_post": y_train_over_post,
        "X_train_under_pre": pd.DataFrame(X_train_under_pre, columns=attribute_names).convert_dtypes(),
        "y_train_under_pre": y_train_under_pre,
        "X_train_under_post": pd.DataFrame(X_train_under_post, columns=attribute_names).convert_dtypes(),
        "y_train_under_post": y_train_under_post,
    }
    return data_dic
# --------------------------------------------------------------------------------------------------------

# Initializing chosen models from hyperparameters file
# --------------------------------------------------------------------------------------------------------
def get_chosen_model(group_str, method_str, model_name):
    # Read sheet corresponding to group and method with tuned models and their hyperparameters
Joaquin Torres's avatar
Joaquin Torres committed
66
    tuned_models_df = pd.read_excel("../model_selection/results/hyperparam/hyperparamers.xlsx", sheet_name=f"{group_str}_{method_str}")
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
    tuned_models_df.columns = ['Model', 'Best Parameters']
    
    # Define the mapping from model abbreviations to sklearn model classes
    model_mapping = {
        'DT': DecisionTreeClassifier,
        'RF': RandomForestClassifier,
        'Bagging': BaggingClassifier,
        'AB': AdaBoostClassifier,
        'XGB': XGBClassifier,
        'LR': LogisticRegression,
        'SVM': SVC,
        'MLP': MLPClassifier
    }
    
    # Access the row for the given model name by checking the first column (index 0)
    row = tuned_models_df[tuned_models_df['Model'] == model_name].iloc[0]

    # Parse the dictionary of parameters from the 'Best Parameters' column
    parameters = ast.literal_eval(row['Best Parameters'])
    
    # Modify parameters based on model specifics or methods if necessary
    if model_name == 'AB':
        parameters['algorithm'] = 'SAMME'
    elif model_name == 'LR':
        parameters['max_iter'] = 1000
    elif model_name == 'SVM':
        parameters['max_iter'] = 1000
        parameters['probability'] = True
    elif model_name == "MLP":
        parameters['max_iter'] = 500
    
    # Add class_weight argument for cost-sensitive learning method
    if 'CW' in method_str:
        if model_name in ['Bagging', 'AB']:
            parameters['estimator'] = DecisionTreeClassifier(class_weight='balanced')
        else:
            parameters['class_weight'] = 'balanced'

    # Fetch the class of the model
    model_class = model_mapping[model_name]

    # Initialize the model with the parameters
    chosen_model = model_class(**parameters)
    # Return if it is a tree model, for SHAP
    is_tree = model_name not in ['LR', 'SVM', 'MLP']
    
    return chosen_model, is_tree
# --------------------------------------------------------------------------------------------------------

if __name__ == "__main__":
    # Setup
    # --------------------------------------------------------------------------------------------------------
    # Retrieve attribute names in order
Joaquin Torres's avatar
Joaquin Torres committed
120
    attribute_names = list(np.load('../EDA/results/feature_names/all_features.npy', allow_pickle=True))
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
    # Reading data
    data_dic = read_training_data(attribute_names)
    method_names = {
        0: "ORIG",
        1: "ORIG_CW",
        2: "OVER",
        3: "UNDER"
    }
    model_choices = {
        "ORIG": "XGB",
        "ORIG_CW": "RF",
        "OVER": "XGB",
        "UNDER": "XGB"
    }
    # --------------------------------------------------------------------------------------------------------

    # Fitting final models with whole training dataset
    # --------------------------------------------------------------------------------------------------------
    for i, group in enumerate(['pre', 'post']):
        for j, method in enumerate(['', '', 'over_', 'under_']):
            print(f"{group}-{method_names[j]}")
            # Get train dataset based on group and method
            X_train = data_dic['X_train_' + method + group]
            y_train = data_dic['y_train_' + method + group]
            method_name = method_names[j]
            # Get chosen tuned model for this group and method context
            model, is_tree = get_chosen_model(group_str=group, method_str=method_name, model_name=model_choices[method_name])
            fitted_model = model.fit(X_train, y_train)
            # Define the file path where you want to save the model
Joaquin Torres's avatar
Joaquin Torres committed
150
            model_save_path = f"./results/fitted_models/{group}_{method_names[j]}_{model_choices[method_name]}.pkl"
151 152
            # Save the model to disk
            with open(model_save_path, 'wb') as f:
Joaquin Torres's avatar
Joaquin Torres committed
153 154
                pickle.dump(fitted_model, f)
print('Successful fitting')