hyperparam_tuning.py 9.09 KB
Newer Older
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
"""
    Selecting best models through cross validation and hyperparameter tunning 
    for each method: 
        1. Original training dataset
        2. Original training dataset - Cost sensitive
        3. Oversampling
        4. Undersampling
"""

# Libraries
# --------------------------------------------------------------------------------------------------------
import pandas as pd
import numpy as np
from xgboost import XGBClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score, make_scorer, precision_score, recall_score
from sklearn.model_selection import StratifiedKFold, cross_validate
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
from scipy.stats import randint, uniform
from sklearn.model_selection import RandomizedSearchCV
# --------------------------------------------------------------------------------------------------------

# Function to read datasets
# --------------------------------------------------------------------------------------------------------
def read_data():
    import numpy as np

    # Load test data
33 34 35 36
    X_test_pre = np.load('../gen_train_data/data/output/pre/X_test_pre.npy', allow_pickle=True)
    y_test_pre = np.load('../gen_train_data/data/output/pre/y_test_pre.npy', allow_pickle=True)
    X_test_post = np.load('../gen_train_data/data/output/post/X_test_post.npy', allow_pickle=True)
    y_test_post = np.load('../gen_train_data/data/output/post/y_test_post.npy', allow_pickle=True)
37 38

    # Load ORIGINAL training data
39 40 41 42
    X_train_pre = np.load('../gen_train_data/data/output/pre/X_train_pre.npy', allow_pickle=True)
    y_train_pre = np.load('../gen_train_data/data/output/pre/y_train_pre.npy', allow_pickle=True)
    X_train_post = np.load('../gen_train_data/data/output/post/X_train_post.npy', allow_pickle=True)
    y_train_post = np.load('../gen_train_data/data/output/post/y_train_post.npy', allow_pickle=True)
43 44

    # Load oversampled training data
45 46 47 48
    X_train_over_pre = np.load('../gen_train_data/data/output/pre/X_train_over_pre.npy', allow_pickle=True)
    y_train_over_pre = np.load('../gen_train_data/data/output/pre/y_train_over_pre.npy', allow_pickle=True)
    X_train_over_post = np.load('../gen_train_data/data/output/post/X_train_over_post.npy', allow_pickle=True)
    y_train_over_post = np.load('../gen_train_data/data/output/post/y_train_over_post.npy', allow_pickle=True)
49 50

    # Load undersampled training data
51 52 53 54
    X_train_under_pre = np.load('../gen_train_data/data/output/pre/X_train_under_pre.npy', allow_pickle=True)
    y_train_under_pre = np.load('../gen_train_data/data/output/pre/y_train_under_pre.npy', allow_pickle=True)
    X_train_under_post = np.load('../gen_train_data/data/output/post/X_train_under_post.npy', allow_pickle=True)
    y_train_under_post = np.load('../gen_train_data/data/output/post/y_train_under_post.npy', allow_pickle=True)
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

    data_dic = {
        "X_test_pre": X_test_pre,
        "y_test_pre": y_test_pre,
        "X_test_post": X_test_post,
        "y_test_post": y_test_post,
        "X_train_pre": X_train_pre,
        "y_train_pre": y_train_pre,
        "X_train_post": X_train_post,
        "y_train_post": y_train_post,
        "X_train_over_pre": X_train_over_pre,
        "y_train_over_pre": y_train_over_pre,
        "X_train_over_post": X_train_over_post,
        "y_train_over_post": y_train_over_post,
        "X_train_under_pre": X_train_under_pre,
        "y_train_under_pre": y_train_under_pre,
        "X_train_under_post": X_train_under_post,
        "y_train_under_post": y_train_under_post,
    }

    return data_dic
# --------------------------------------------------------------------------------------------------------

if __name__ == "__main__":

    # Reading training data
    data_dic = read_data()

    # Defining the models to train
    # --------------------------------------------------------------------------------------------------------
    # 1. No class weight
    models_1 = {"DT" : DecisionTreeClassifier(), 
87 88 89 90 91 92 93 94
            "RF" : RandomForestClassifier(), 
            "Bagging" : BaggingClassifier(),
            "AB" : AdaBoostClassifier(), 
            "XGB": XGBClassifier(),
            "LR" : LogisticRegression(max_iter=1000), 
            "ElNet" : LogisticRegression(max_iter=1000, penalty='elasticnet'), 
            "SVM" : SVC(probability=True), 
            "MLP" : MLPClassifier(max_iter=500)
95 96
            }
    
97
    # 2. Class weight: cost-sensitive learning
98
    models_2 = {"DT" : DecisionTreeClassifier(class_weight='balanced'), 
99 100 101
            "RF" : RandomForestClassifier(class_weight='balanced'), 
            "Bagging" : BaggingClassifier(estimator= DecisionTreeClassifier(class_weight='balanced')),
            "AB" : AdaBoostClassifier(estimator= DecisionTreeClassifier(class_weight='balanced')),  
102
            # "XGB": XGBClassifier(), # <-
103 104 105 106
            "LR" : LogisticRegression(max_iter=1000, class_weight='balanced'), 
            "ElNet" : LogisticRegression(max_iter=1000, penalty='elasticnet', class_weight='balanced'), 
            "SVM" : SVC(probability=True, class_weight='balanced'), 
            # "MLP" : MLPClassifier(max_iter=500)
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
            }

    # Hyperparameter tuning setup
    # --------------------------------------------------------------------------------------------------------
    hyperparameters = {
        "DT": {'splitter': ['best', 'random'], 
            'max_features': ['sqrt', 'log2'], 
            'criterion': ['gini', 'entropy', 'log_loss']},
        "RF": {'n_estimators': randint(100, 250), 
            'max_features': ['sqrt', 'log2'], 
            'criterion': ['gini', 'entropy']},
        "Bagging": {'n_estimators': randint(10, 100), 
                    'max_samples': [0.8, 1.0], 
                    'max_features': [0.8, 1.0], 
                    'warm_start': [True, False]},
        "AB": {'n_estimators': randint(50, 150), 
            'learning_rate': uniform(0.8, 1.2)},
        "XGB": {'n_estimators': randint(100, 1000), 
                'max_depth': randint(3, 10), 
                'learning_rate': uniform(0.01, 0.3)},
        "LR": {'penalty': ['l1', 'l2', None], 
            'solver': ['lbfgs', 'sag', 'saga']},
        "EL": {'solver': ['lbfgs', 'sag', 'saga']},
        "SVM": {'C': uniform(0.8, 1.2), 
                'kernel': ['linear', 'poly', 'rbf', 'sigmoid']},
        "MLP": {'activation': ['identity', 'logistic', 'tanh', 'relu'], 
                'hidden_layer_sizes': randint(50, 150), 
                'learning_rate': ['constant', 'invscaling', 'adaptive']}
    }
    # --------------------------------------------------------------------------------------------------------

    # Cross-validation setup
    # --------------------------------------------------------------------------------------------------------
    # Defining cross-validation protocol
    cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)
    method_names = {
        0: "ORIG",
        1: "ORIG_CW",
        2: "OVER",
        3: "UNDER"
    }
    # --------------------------------------------------------------------------------------------------------

    # Hyperparameter tuning loop and exporting results
    # --------------------------------------------------------------------------------------------------------
    # Store each df as a sheet in an excel file
    sheets_dict = {}
    for i, group in enumerate(['pre', 'post']):
155
        print(group, end = ' ')
156
        for j, method in enumerate(['', '', 'over_', 'under_']):
157
            print(method, end = ' ')
158 159 160 161 162 163 164 165
            # Get dataset based on group and method
            X = data_dic['X_train_' + method + group]
            y = data_dic['y_train_' + method + group]
            # Use group of models with class weight if needed
            models = models_2 if j == 2 else models_1 
            # Save results: params and best score for each of the mdodels of this method and group
            hyperparam_df = pd.DataFrame(index=list(models.keys()), columns=['Parameters','Score'])
            for model_name, model in models.items():
166
                print(model_name + "\n\n")
167 168 169 170 171 172 173 174 175 176 177 178
                # Find optimal hyperparams for curr model
                params = hyperparameters[model_name]
                search = RandomizedSearchCV(model, param_distributions=params, cv=cv, n_jobs=1, scoring='precision')
                search.fit(X,y)
                hyperparam_df.at[model_name,'Parameters']=search.best_params_
                hyperparam_df.at[model_name,'Score']=round(search.best_score_,4)
            
            # Store the DataFrame in the dictionary with a unique key for each sheet
            sheet_name = f"{group}_{method_names[j]}"
            sheets_dict[sheet_name] = hyperparam_df

    # Write results to Excel file
179
    with pd.ExcelWriter('./output/hyperparam.xlsx') as writer:
180 181 182 183 184
        for sheet_name, data in sheets_dict.items():
            data.to_excel(writer, sheet_name=sheet_name)
    # --------------------------------------------------------------------------------------------------------