833 lines
No EOL
35 KiB
Python
Executable file
833 lines
No EOL
35 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
Created on Fri Mar 4 15:25:33 2022
|
|
|
|
@author: tanu
|
|
"""
|
|
#%%
|
|
import os, sys
|
|
import pandas as pd
|
|
import numpy as np
|
|
import pprint as pp
|
|
from copy import deepcopy
|
|
from sklearn import linear_model
|
|
from sklearn import datasets
|
|
from collections import Counter
|
|
|
|
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
|
|
from sklearn.linear_model import RidgeClassifier, RidgeClassifierCV, SGDClassifier, PassiveAggressiveClassifier
|
|
|
|
from sklearn.naive_bayes import BernoulliNB
|
|
from sklearn.neighbors import KNeighborsClassifier
|
|
from sklearn.svm import SVC
|
|
from sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier
|
|
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier, GradientBoostingClassifier, BaggingClassifier
|
|
from sklearn.naive_bayes import GaussianNB
|
|
from sklearn.gaussian_process import GaussianProcessClassifier, kernels
|
|
from sklearn.gaussian_process.kernels import RBF, DotProduct, Matern, RationalQuadratic, WhiteKernel
|
|
|
|
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
|
|
from sklearn.neural_network import MLPClassifier
|
|
|
|
from sklearn.svm import SVC
|
|
from xgboost import XGBClassifier
|
|
from sklearn.naive_bayes import MultinomialNB
|
|
from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder
|
|
|
|
from sklearn.compose import ColumnTransformer
|
|
from sklearn.compose import make_column_transformer
|
|
|
|
from sklearn.metrics import make_scorer, confusion_matrix, accuracy_score, balanced_accuracy_score, precision_score, average_precision_score, recall_score
|
|
from sklearn.metrics import roc_auc_score, roc_curve, f1_score, matthews_corrcoef, jaccard_score, classification_report
|
|
|
|
# added
|
|
from sklearn.model_selection import train_test_split, cross_validate, cross_val_score, LeaveOneOut, KFold, RepeatedKFold, cross_val_predict
|
|
|
|
from sklearn.model_selection import train_test_split, cross_validate, cross_val_score
|
|
from sklearn.model_selection import StratifiedKFold,RepeatedStratifiedKFold, RepeatedKFold
|
|
|
|
from sklearn.pipeline import Pipeline, make_pipeline
|
|
|
|
from sklearn.feature_selection import RFE, RFECV
|
|
|
|
import itertools
|
|
import seaborn as sns
|
|
import matplotlib.pyplot as plt
|
|
|
|
from statistics import mean, stdev, median, mode
|
|
|
|
from imblearn.over_sampling import RandomOverSampler
|
|
from imblearn.under_sampling import RandomUnderSampler
|
|
from imblearn.over_sampling import SMOTE
|
|
from sklearn.datasets import make_classification
|
|
from imblearn.combine import SMOTEENN
|
|
from imblearn.combine import SMOTETomek
|
|
|
|
from imblearn.over_sampling import SMOTENC
|
|
from imblearn.under_sampling import EditedNearestNeighbours
|
|
from imblearn.under_sampling import RepeatedEditedNearestNeighbours
|
|
|
|
from sklearn.model_selection import GridSearchCV
|
|
from sklearn.base import BaseEstimator
|
|
from sklearn.impute import KNNImputer as KNN
|
|
import json
|
|
import argparse
|
|
import re
|
|
#%% GLOBALS
|
|
rs = {'random_state': 42}
|
|
njobs = {'n_jobs': 10}
|
|
|
|
scoring_fn = ({ 'mcc' : make_scorer(matthews_corrcoef)
|
|
, 'fscore' : make_scorer(f1_score)
|
|
, 'precision' : make_scorer(precision_score)
|
|
, 'recall' : make_scorer(recall_score)
|
|
, 'accuracy' : make_scorer(accuracy_score)
|
|
, 'roc_auc' : make_scorer(roc_auc_score)
|
|
, 'jcc' : make_scorer(jaccard_score)
|
|
})
|
|
|
|
skf_cv = StratifiedKFold(n_splits = 10
|
|
#, shuffle = False, random_state= None)
|
|
, shuffle = True,**rs)
|
|
|
|
rskf_cv = RepeatedStratifiedKFold(n_splits = 10
|
|
, n_repeats = 3
|
|
, **rs)
|
|
|
|
mcc_score_fn = {'mcc': make_scorer(matthews_corrcoef)}
|
|
jacc_score_fn = {'jcc': make_scorer(jaccard_score)}
|
|
|
|
###############################################################################
|
|
score_type_ordermapD = { 'mcc' : 1
|
|
, 'fscore' : 2
|
|
, 'jcc' : 3
|
|
, 'precision' : 4
|
|
, 'recall' : 5
|
|
, 'accuracy' : 6
|
|
, 'roc_auc' : 7
|
|
, 'TN' : 8
|
|
, 'FP' : 9
|
|
, 'FN' : 10
|
|
, 'TP' : 11
|
|
, 'trainingY_neg': 12
|
|
, 'trainingY_pos': 13
|
|
, 'blindY_neg' : 14
|
|
, 'blindY_pos' : 15
|
|
, 'fit_time' : 16
|
|
, 'score_time' : 17
|
|
}
|
|
|
|
scoreCV_mapD = {'test_mcc' : 'MCC'
|
|
, 'test_fscore' : 'F1'
|
|
, 'test_precision' : 'Precision'
|
|
, 'test_recall' : 'Recall'
|
|
, 'test_accuracy' : 'Accuracy'
|
|
, 'test_roc_auc' : 'ROC_AUC'
|
|
, 'test_jcc' : 'JCC'
|
|
}
|
|
|
|
scoreBT_mapD = {'bts_mcc' : 'MCC'
|
|
, 'bts_fscore' : 'F1'
|
|
, 'bts_precision' : 'Precision'
|
|
, 'bts_recall' : 'Recall'
|
|
, 'bts_accuracy' : 'Accuracy'
|
|
, 'bts_roc_auc' : 'ROC_AUC'
|
|
, 'bts_jcc' : 'JCC'
|
|
}
|
|
|
|
#%%############################################################################
|
|
############################
|
|
# MultModelsCl()
|
|
# Run Multiple Classifiers
|
|
############################
|
|
# Multiple Classification - Model Pipeline
|
|
def MultModelsCl(input_df, target, skf_cv
|
|
, blind_test_df
|
|
, blind_test_target
|
|
, tts_split_type
|
|
, resampling_type = 'none' # default
|
|
, add_cm = True # adds confusion matrix based on cross_val_predict
|
|
, add_yn = True # adds target var class numbers
|
|
, var_type = ['numerical', 'categorical','mixed']
|
|
, return_formatted_output = True):
|
|
|
|
'''
|
|
@ param input_df: input features
|
|
@ type: df with input features WITHOUT the target variable
|
|
|
|
@param target: target (or output) feature
|
|
@type: df or np.array or Series
|
|
|
|
@param skv_cv: stratifiedK fold int or object to allow shuffle and random state to pass
|
|
@type: int or StratifiedKfold()
|
|
|
|
@var_type: numerical, categorical and mixed to determine what col_transform to apply (MinMaxScalar and/or one-ho t encoder)
|
|
@type: list
|
|
|
|
returns
|
|
Dict containing multiple classification scores for each model and mean of each Stratified Kfold including training
|
|
'''
|
|
|
|
#======================================================
|
|
# Determine categorical and numerical features
|
|
#======================================================
|
|
numerical_ix = input_df.select_dtypes(include=['int64', 'float64']).columns
|
|
numerical_ix
|
|
categorical_ix = input_df.select_dtypes(include=['object', 'bool']).columns
|
|
categorical_ix
|
|
|
|
#======================================================
|
|
# Determine preprocessing steps ~ var_type
|
|
#======================================================
|
|
if var_type == 'numerical':
|
|
t = [('num', MinMaxScaler(), numerical_ix)]
|
|
|
|
if var_type == 'categorical':
|
|
t = [('cat', OneHotEncoder(), categorical_ix)]
|
|
|
|
if var_type == 'mixed':
|
|
t = [('num', MinMaxScaler(), numerical_ix)
|
|
, ('cat', OneHotEncoder(), categorical_ix) ]
|
|
|
|
col_transform = ColumnTransformer(transformers = t
|
|
, remainder='passthrough')
|
|
|
|
#======================================================
|
|
# Specify multiple Classification Models
|
|
#======================================================
|
|
models = [('AdaBoost Classifier' , AdaBoostClassifier(**rs) )
|
|
, ('Bagging Classifier' , BaggingClassifier(**rs, **njobs, bootstrap = True, oob_score = True) )
|
|
, ('Decision Tree' , DecisionTreeClassifier(**rs) )
|
|
, ('Extra Tree' , ExtraTreeClassifier(**rs) )
|
|
, ('Extra Trees' , ExtraTreesClassifier(**rs) )
|
|
, ('Gradient Boosting' , GradientBoostingClassifier(**rs) )
|
|
, ('Gaussian NB' , GaussianNB() )
|
|
, ('Gaussian Process' , GaussianProcessClassifier(**rs) )
|
|
, ('K-Nearest Neighbors' , KNeighborsClassifier() )
|
|
, ('LDA' , LinearDiscriminantAnalysis() )
|
|
, ('Logistic Regression' , LogisticRegression(**rs) )
|
|
, ('Logistic RegressionCV' , LogisticRegressionCV(cv = 3, **rs))
|
|
, ('MLP' , MLPClassifier(max_iter = 500, **rs) )
|
|
, ('Multinomial' , MultinomialNB() )
|
|
, ('Naive Bayes' , BernoulliNB() )
|
|
, ('Passive Aggresive' , PassiveAggressiveClassifier(**rs, **njobs) )
|
|
, ('QDA' , QuadraticDiscriminantAnalysis() )
|
|
, ('Random Forest' , RandomForestClassifier(**rs, n_estimators = 1000 ) )
|
|
, ('Random Forest2' , RandomForestClassifier(min_samples_leaf = 5
|
|
, n_estimators = 1000
|
|
, bootstrap = True
|
|
, oob_score = True
|
|
, **njobs
|
|
, **rs
|
|
, max_features = 'auto') )
|
|
, ('Ridge Classifier' , RidgeClassifier(**rs) )
|
|
, ('Ridge ClassifierCV' , RidgeClassifierCV(cv = 3) )
|
|
, ('SVC' , SVC(**rs) )
|
|
, ('Stochastic GDescent' , SGDClassifier(**rs, **njobs) )
|
|
, ('XGBoost' , XGBClassifier(**rs, verbosity = 0, use_label_encoder =False) )
|
|
]
|
|
|
|
mm_skf_scoresD = {}
|
|
|
|
print('\n==============================================================\n'
|
|
, '\nRunning several classification models (n):', len(models)
|
|
,'\nList of models:')
|
|
for m in models:
|
|
print(m)
|
|
print('\n================================================================\n')
|
|
|
|
index = 1
|
|
for model_name, model_fn in models:
|
|
print('\nRunning classifier:', index
|
|
, '\nModel_name:' , model_name
|
|
, '\nModel func:' , model_fn)
|
|
index = index+1
|
|
|
|
model_pipeline = Pipeline([
|
|
('prep' , col_transform)
|
|
, ('model' , model_fn)])
|
|
|
|
print('\nRunning model pipeline:', model_pipeline)
|
|
skf_cv_modD = cross_validate(model_pipeline
|
|
, input_df
|
|
, target
|
|
, cv = skf_cv
|
|
, scoring = scoring_fn
|
|
, return_train_score = True)
|
|
|
|
#######################################################################
|
|
#======================================================
|
|
# Option: Add confusion matrix from cross_val_predict
|
|
# Understand and USE with caution
|
|
# cross_val_score, cross_val_predict, "Passing these predictions into an evaluation metric may not be a valid way to measure generalization performance. Results can differ from cross_validate and cross_val_score unless all tests sets have equal size and the metric decomposes over samples."
|
|
# https://stackoverflow.com/questions/65645125/producing-a-confusion-matrix-with-cross-validate
|
|
#======================================================
|
|
if add_cm:
|
|
|
|
#-----------------------------------------------------------
|
|
# Initialise dict of Confusion Matrix (cm)
|
|
#-----------------------------------------------------------
|
|
cmD = {}
|
|
|
|
# Calculate cm
|
|
y_pred = cross_val_predict(model_pipeline, input_df, target, cv = skf_cv, **njobs)
|
|
#_tn, _fp, _fn, _tp = confusion_matrix(y_pred, y).ravel() # internally
|
|
tn, fp, fn, tp = confusion_matrix(y_pred, target).ravel()
|
|
|
|
# Build dict
|
|
|
|
cmD = {'TN' : tn
|
|
, 'FP': fp
|
|
, 'FN': fn
|
|
, 'TP': tp}
|
|
#---------------------------------
|
|
# Update cv dict with cmD and tbtD
|
|
#----------------------------------
|
|
skf_cv_modD.update(cmD)
|
|
else:
|
|
skf_cv_modD = skf_cv_modD
|
|
#######################################################################
|
|
#=============================================
|
|
# Option: Add targety numbers for data
|
|
#=============================================
|
|
if add_yn:
|
|
|
|
#-----------------------------------------------------------
|
|
# Initialise dict of target numbers: training and blind (tbt)
|
|
#-----------------------------------------------------------
|
|
tbtD = {}
|
|
|
|
# training y
|
|
tyn = Counter(target)
|
|
tyn_neg = tyn[0]
|
|
tyn_pos = tyn[1]
|
|
|
|
# blind test y
|
|
btyn = Counter(blind_test_target)
|
|
btyn_neg = btyn[0]
|
|
btyn_pos = btyn[1]
|
|
|
|
# Build dict
|
|
tbtD = {'n_trainingY_neg' : tyn_neg
|
|
, 'n_trainingY_pos' : tyn_pos
|
|
, 'n_blindY_neg' : btyn_neg
|
|
, 'n_blindY_pos' : btyn_pos}
|
|
|
|
#---------------------------------
|
|
# Update cv dict with cmD and tbtD
|
|
#----------------------------------
|
|
skf_cv_modD.update(tbtD)
|
|
else:
|
|
skf_cv_modD = skf_cv_modD
|
|
|
|
#######################################################################
|
|
#==============================
|
|
# Extract mean values for CV
|
|
#==============================
|
|
mm_skf_scoresD[model_name] = {}
|
|
|
|
for key, value in skf_cv_modD.items():
|
|
print('\nkey:', key, '\nvalue:', value)
|
|
print('\nmean value:', np.mean(value))
|
|
mm_skf_scoresD[model_name][key] = round(np.mean(value),2)
|
|
|
|
#return(mm_skf_scoresD)
|
|
#%%
|
|
#=========================
|
|
# Blind test: BTS results
|
|
#=========================
|
|
# Build the final results with all scores for the model
|
|
#bts_predict = gscv_fs.predict(blind_test_df)
|
|
model_pipeline.fit(input_df, target)
|
|
bts_predict = model_pipeline.predict(blind_test_df)
|
|
|
|
bts_mcc_score = round(matthews_corrcoef(blind_test_target, bts_predict),2)
|
|
print('\nMCC on Blind test:' , bts_mcc_score)
|
|
print('\nAccuracy on Blind test:', round(accuracy_score(blind_test_target, bts_predict),2))
|
|
|
|
# Diff b/w train and bts test scores
|
|
# train_test_diff_MCC = cvtrain_mcc - bts_mcc_score
|
|
# print('\nDiff b/w train and blind test score (MCC):', train_test_diff)
|
|
|
|
mm_skf_scoresD[model_name]['bts_mcc'] = bts_mcc_score
|
|
mm_skf_scoresD[model_name]['bts_fscore'] = round(f1_score(blind_test_target, bts_predict),2)
|
|
mm_skf_scoresD[model_name]['bts_precision'] = round(precision_score(blind_test_target, bts_predict),2)
|
|
mm_skf_scoresD[model_name]['bts_recall'] = round(recall_score(blind_test_target, bts_predict),2)
|
|
mm_skf_scoresD[model_name]['bts_accuracy'] = round(accuracy_score(blind_test_target, bts_predict),2)
|
|
mm_skf_scoresD[model_name]['bts_roc_auc'] = round(roc_auc_score(blind_test_target, bts_predict),2)
|
|
mm_skf_scoresD[model_name]['bts_jcc'] = round(jaccard_score(blind_test_target, bts_predict),2)
|
|
#mm_skf_scoresD[model_name]['diff_mcc'] = train_test_diff_MCC
|
|
|
|
#return(mm_skf_scoresD)
|
|
#%%
|
|
# ADD more info: meta data related to input and blind and resampling
|
|
|
|
# target numbers: training
|
|
yc1 = Counter(target)
|
|
yc1_ratio = yc1[0]/yc1[1]
|
|
|
|
# target numbers: test
|
|
yc2 = Counter(blind_test_target)
|
|
yc2_ratio = yc2[0]/yc2[1]
|
|
|
|
mm_skf_scoresD[model_name]['resampling'] = resampling_type
|
|
|
|
mm_skf_scoresD[model_name]['n_training_size'] = len(input_df)
|
|
mm_skf_scoresD[model_name]['n_trainingY_ratio'] = round(yc1_ratio, 2)
|
|
|
|
mm_skf_scoresD[model_name]['n_test_size'] = len(blind_test_df)
|
|
mm_skf_scoresD[model_name]['n_testY_ratio'] = round(yc2_ratio,2)
|
|
mm_skf_scoresD[model_name]['n_features'] = len(input_df.columns)
|
|
mm_skf_scoresD[model_name]['tts_split'] = tts_split_type
|
|
|
|
#return(mm_skf_scoresD)
|
|
#============================
|
|
# Process the dict to have WF
|
|
#============================
|
|
if return_formatted_output:
|
|
CV_BT_metaDF = ProcessMultModelsCl(mm_skf_scoresD)
|
|
return(CV_BT_metaDF)
|
|
else:
|
|
return(mm_skf_scoresD)
|
|
|
|
#%% Process output function ###################################################
|
|
############################
|
|
# ProcessMultModelsCl()
|
|
############################
|
|
#Processes the dict from above if use_formatted_output = True
|
|
|
|
def ProcessMultModelsCl(inputD = {}):
|
|
|
|
scoresDF = pd.DataFrame(inputD)
|
|
|
|
#------------------------
|
|
# Extracting split_name
|
|
#-----------------------
|
|
tts_split_nameL = []
|
|
for k,v in inputD.items():
|
|
tts_split_nameL = tts_split_nameL + [v['tts_split']]
|
|
|
|
if len(set(tts_split_nameL)) == 1:
|
|
tts_split_name = str(list(set(tts_split_nameL))[0])
|
|
print('\nExtracting tts_split_name:', tts_split_name)
|
|
|
|
#------------------------
|
|
# WF: only CV and BTS
|
|
#-----------------------
|
|
scoresDFT = scoresDF.T
|
|
|
|
scoresDF_CV = scoresDFT.filter(regex='^test_.*$', axis = 1); scoresDF_CV.columns
|
|
# map colnames for consistency to allow concatenting
|
|
scoresDF_CV.columns = scoresDF_CV.columns.map(scoreCV_mapD); scoresDF_CV.columns
|
|
scoresDF_CV['source_data'] = 'CV'
|
|
|
|
scoresDF_BT = scoresDFT.filter(regex='^bts_.*$', axis = 1); scoresDF_BT.columns
|
|
# map colnames for consistency to allow concatenting
|
|
scoresDF_BT.columns = scoresDF_BT.columns.map(scoreBT_mapD); scoresDF_BT.columns
|
|
scoresDF_BT['source_data'] = 'BT'
|
|
|
|
# dfs_combine_wf = [baseline_BT, smnc_BT, ros_BT, rus_BT, rouC_BT,
|
|
# baseline_CV, smnc_CV, ros_CV, rus_CV, rouC_CV]
|
|
|
|
#baseline_all = baseline_all_scores.filter(regex = 'bts_.*|test_.*|.*_time|TN|FP|FN|TP|.*_neg|.*_pos', axis = 0)
|
|
|
|
#metaDF = scoresDFT.filter(regex='training_size|blind_test_size|_time|TN|FP|FN|TP|.*_neg|.*_pos|resampling', axis = 1); scoresDF_BT.columns
|
|
#metaDF = scoresDFT.filter(regex='n_.*$|_time|TN|FP|FN|TP|.*_neg|.*_pos|resampling|tts.*', axis = 1); metaDF.columns
|
|
metaDF = scoresDFT.filter(regex='^(?!test_.*$|bts_.*$|train_.*$).*'); metaDF.columns
|
|
|
|
print('\nTotal cols in each df:'
|
|
, '\nCV df:', len(scoresDF_CV.columns)
|
|
, '\nBT_df:', len(scoresDF_BT.columns)
|
|
, '\nmetaDF:', len(metaDF.columns))
|
|
|
|
if len(scoresDF_CV.columns) == len(scoresDF_BT.columns):
|
|
print('\nFirst proceeding to rowbind CV and BT dfs:')
|
|
expected_ncols_out = len(scoresDF_BT.columns) + len(metaDF.columns)
|
|
print('\nFinal output should have:', expected_ncols_out, 'columns' )
|
|
|
|
#-----------------
|
|
# Combine WF
|
|
#-----------------
|
|
dfs_combine_wf = [scoresDF_CV, scoresDF_BT]
|
|
|
|
print('\nCombinig', len(dfs_combine_wf), 'using pd.concat by row ~ rowbind'
|
|
, '\nChecking Dims of df to combine:'
|
|
, '\nDim of CV:', scoresDF_CV.shape
|
|
, '\nDim of BT:', scoresDF_BT.shape)
|
|
#print(scoresDF_CV)
|
|
#print(scoresDF_BT)
|
|
|
|
dfs_nrows_wf = []
|
|
for df in dfs_combine_wf:
|
|
dfs_nrows_wf = dfs_nrows_wf + [len(df)]
|
|
dfs_nrows_wf = max(dfs_nrows_wf)
|
|
|
|
dfs_ncols_wf = []
|
|
for df in dfs_combine_wf:
|
|
dfs_ncols_wf = dfs_ncols_wf + [len(df.columns)]
|
|
dfs_ncols_wf = max(dfs_ncols_wf)
|
|
print(dfs_ncols_wf)
|
|
|
|
expected_nrows_wf = len(dfs_combine_wf) * dfs_nrows_wf
|
|
expected_ncols_wf = dfs_ncols_wf
|
|
|
|
common_cols_wf = list(set.intersection(*(set(df.columns) for df in dfs_combine_wf)))
|
|
print('\nNumber of Common columns:', dfs_ncols_wf
|
|
, '\nThese are:', common_cols_wf)
|
|
|
|
if len(common_cols_wf) == dfs_ncols_wf :
|
|
combined_baseline_wf = pd.concat([df[common_cols_wf] for df in dfs_combine_wf], ignore_index=False)
|
|
print('\nConcatenating dfs with different resampling methods [WF]:'
|
|
, '\nSplit type:', tts_split_name
|
|
, '\nNo. of dfs combining:', len(dfs_combine_wf))
|
|
#print('\n================================================^^^^^^^^^^^^')
|
|
if len(combined_baseline_wf) == expected_nrows_wf and len(combined_baseline_wf.columns) == expected_ncols_wf:
|
|
#print('\n================================================^^^^^^^^^^^^')
|
|
|
|
print('\nPASS:', len(dfs_combine_wf), 'dfs successfully combined'
|
|
, '\nnrows in combined_df_wf:', len(combined_baseline_wf)
|
|
, '\nncols in combined_df_wf:', len(combined_baseline_wf.columns))
|
|
else:
|
|
print('\nFAIL: concatenating failed'
|
|
, '\nExpected nrows:', expected_nrows_wf
|
|
, '\nGot:', len(combined_baseline_wf)
|
|
, '\nExpected ncols:', expected_ncols_wf
|
|
, '\nGot:', len(combined_baseline_wf.columns))
|
|
sys.exit('\nFIRST IF FAILS')
|
|
else:
|
|
print('\nConcatenting dfs not possible [WF],check numbers ')
|
|
|
|
#-------------------------------------
|
|
# Combine WF+Metadata: Final output
|
|
#-------------------------------------
|
|
# checking indices for the dfs to combine:
|
|
c1L = list(set(combined_baseline_wf.index))
|
|
c2L = list(metaDF.index)
|
|
|
|
#if set(c1L) == set(c2L):
|
|
if set(c1L) == set(c2L) and all(x in c2L for x in c1L) and all(x in c1L for x in c2L):
|
|
print('\nPASS: proceeding to merge metadata with CV and BT dfs')
|
|
combDF = pd.merge(combined_baseline_wf, metaDF, left_index = True, right_index = True)
|
|
else:
|
|
sys.exit('\nFAIL: Could not merge metadata with CV and BT dfs')
|
|
|
|
if len(combDF.columns) == expected_ncols_out:
|
|
print('\nPASS: Combined df has expected ncols')
|
|
else:
|
|
sys.exit('\nFAIL: Length mismatch for combined_df')
|
|
|
|
print('\nAdding column: Model_name')
|
|
|
|
combDF['Model_name'] = combDF.index
|
|
|
|
print('\n========================================================='
|
|
, '\nSUCCESS: Ran multiple classifiers'
|
|
, '\n=======================================================')
|
|
|
|
#resampling_methods_wf = combined_baseline_wf[['resampling']]
|
|
#resampling_methods_wf = resampling_methods_wf.drop_duplicates()
|
|
#, '\n', resampling_methods_wf)
|
|
|
|
return combDF
|
|
|
|
###############################################################################
|
|
#%% Feature selection function ################################################
|
|
############################
|
|
# fsgs_rfecv()
|
|
############################
|
|
# Run FS using some classifier models
|
|
#
|
|
def fsgs_rfecv(input_df
|
|
, target
|
|
, param_gridLd = [{'fs__min_features_to_select' : [1]}]
|
|
, blind_test_df = pd.DataFrame()
|
|
, blind_test_target = pd.Series(dtype = 'int64')
|
|
, estimator = LogisticRegression(**rs) # placeholder
|
|
, use_fs = False # uses estimator as the RFECV parameter for fs. Set to TRUE if you want to supply custom_fs as shown below
|
|
, custom_fs = RFECV(DecisionTreeClassifier(**rs) , cv = skf_cv, scoring = 'matthews_corrcoef')
|
|
, cv_method = skf_cv
|
|
, var_type = ['numerical', 'categorical' , 'mixed']
|
|
, verbose = 3
|
|
):
|
|
'''
|
|
returns
|
|
Dict containing results from FS and hyperparam tuning for a given estiamtor
|
|
|
|
>>> ADD MORE <<<
|
|
|
|
optimised/selected based on mcc
|
|
|
|
'''
|
|
###########################################################################
|
|
#================================================
|
|
# Determine categorical and numerical features
|
|
#================================================
|
|
numerical_ix = input_df.select_dtypes(include=['int64', 'float64']).columns
|
|
numerical_ix
|
|
categorical_ix = input_df.select_dtypes(include=['object', 'bool']).columns
|
|
categorical_ix
|
|
|
|
#================================================
|
|
# Determine preprocessing steps ~ var_type
|
|
#================================================
|
|
if var_type == 'numerical':
|
|
t = [('num', MinMaxScaler(), numerical_ix)]
|
|
|
|
if var_type == 'categorical':
|
|
t = [('cat', OneHotEncoder(), categorical_ix)]
|
|
|
|
if var_type == 'mixed':
|
|
t = [('cat', OneHotEncoder(), categorical_ix)
|
|
, ('num', MinMaxScaler(), numerical_ix)]
|
|
|
|
col_transform = ColumnTransformer(transformers = t
|
|
, remainder='passthrough')
|
|
|
|
###########################################################################
|
|
#==================================================
|
|
# Create var_type ~ column names
|
|
# using one hot encoder with RFECV means
|
|
# the names internally are lost. Hence
|
|
# fit col_transformeer to my input_df and get
|
|
# all the column names out and stored in a var
|
|
# to allow the 'selected features' to be subsetted
|
|
# from the numpy boolean array
|
|
#=================================================
|
|
col_transform.fit(input_df)
|
|
col_transform.get_feature_names_out()
|
|
|
|
var_type_colnames = col_transform.get_feature_names_out()
|
|
var_type_colnames = pd.Index(var_type_colnames)
|
|
|
|
if var_type == 'mixed':
|
|
print('\nVariable type is:', var_type
|
|
, '\nNo. of columns in input_df:', len(input_df.columns)
|
|
, '\nNo. of columns post one hot encoder:', len(var_type_colnames))
|
|
else:
|
|
print('\nNo. of columns in input_df:', len(input_df.columns))
|
|
|
|
#==================================
|
|
# Build FS with supplied estimator
|
|
#==================================
|
|
if use_fs:
|
|
fs = custom_fs
|
|
else:
|
|
fs = RFECV(estimator, cv = skf_cv, scoring = 'matthews_corrcoef')
|
|
|
|
#==================================
|
|
# Build basic param grid
|
|
#==================================
|
|
# param_gridD = [
|
|
# {'fs__min_features_to_select' : [1]
|
|
# }]
|
|
|
|
############################################################################
|
|
# Create Pipeline object
|
|
pipe = Pipeline([
|
|
('pre', col_transform),
|
|
('fs', fs),
|
|
('clf', estimator)])
|
|
############################################################################
|
|
# Define GridSearchCV
|
|
gscv_fs = GridSearchCV(pipe
|
|
#, param_gridLd = param_gridD
|
|
, param_gridLd
|
|
, cv = cv_method
|
|
, scoring = scoring_fn
|
|
, refit = 'mcc'
|
|
, verbose = 3
|
|
, return_train_score = True
|
|
, **njobs)
|
|
|
|
gscv_fs.fit(input_df, target)
|
|
|
|
###########################################################################
|
|
# Get best param and scores out
|
|
gscv_fs.best_params_
|
|
gscv_fs.best_score_
|
|
|
|
# Training best score corresponds to the max of the mean_test<score>
|
|
train_bscore = round(gscv_fs.best_score_, 2); train_bscore
|
|
print('\nTraining best score (MCC):', train_bscore)
|
|
gscv_fs.cv_results_['mean_test_mcc']
|
|
round(gscv_fs.cv_results_['mean_test_mcc'].max(),2)
|
|
round(np.nanmax(gscv_fs.cv_results_['mean_test_mcc']),2)
|
|
|
|
check_train_score = [round(gscv_fs.cv_results_['mean_test_mcc'].max(),2)
|
|
, round(np.nanmax(gscv_fs.cv_results_['mean_test_mcc']),2)]
|
|
|
|
check_train_score = np.nanmax(check_train_score)
|
|
|
|
# Training results
|
|
gscv_tr_resD = gscv_fs.cv_results_
|
|
mod_refit_param = gscv_fs.refit
|
|
|
|
# sanity check
|
|
if train_bscore == check_train_score:
|
|
print('\nVerified training score (MCC):', train_bscore )
|
|
else:
|
|
sys.exit('\nTraining score could not be internatlly verified. Please check training results dict')
|
|
|
|
#-------------------------
|
|
# Dict of CV results
|
|
#-------------------------
|
|
cv_allD = gscv_fs.cv_results_
|
|
cvdf0 = pd.DataFrame(cv_allD)
|
|
cvdf = cvdf0.filter(regex='mean_test', axis = 1)
|
|
cvdfT = cvdf.T
|
|
cvdfT.columns = ['cv_score']
|
|
cvdfTr = cvdfT.loc[:,'cv_score'].round(decimals = 2) # round values
|
|
cvD = cvdfTr.to_dict()
|
|
print('\n CV results dict generated for:', len(scoring_fn), 'scores'
|
|
, '\nThese are:', scoring_fn.keys())
|
|
|
|
#-------------------------
|
|
# Blind test: REAL check!
|
|
#-------------------------
|
|
#tp = gscv_fs.predict(X_bts)
|
|
tp = gscv_fs.predict(blind_test_df)
|
|
|
|
print('\nMCC on Blind test:' , round(matthews_corrcoef(blind_test_target, tp),2))
|
|
print('\nAccuracy on Blind test:', round(accuracy_score(blind_test_target, tp),2))
|
|
|
|
#=================
|
|
# info extraction
|
|
#=================
|
|
# gives input vals??
|
|
gscv_fs._check_n_features
|
|
|
|
# gives gscv params used
|
|
gscv_fs._get_param_names()
|
|
|
|
# gives ??
|
|
gscv_fs.best_estimator_
|
|
gscv_fs.best_params_ # gives best estimator params as a dict
|
|
gscv_fs.best_estimator_._final_estimator # similar to above, doesn't contain max_iter
|
|
gscv_fs.best_estimator_.named_steps['fs'].get_support()
|
|
gscv_fs.best_estimator_.named_steps['fs'].ranking_ # array of ranks for the features
|
|
|
|
gscv_fs.best_estimator_.named_steps['fs'].grid_scores_.mean()
|
|
gscv_fs.best_estimator_.named_steps['fs'].grid_scores_.max()
|
|
#gscv_fs.best_estimator_.named_steps['fs'].grid_scores_
|
|
|
|
estimator_mask = gscv_fs.best_estimator_.named_steps['fs'].get_support()
|
|
|
|
|
|
############################################################################
|
|
#============
|
|
# FS results
|
|
#============
|
|
# Now get the features out
|
|
|
|
#--------------
|
|
# All features
|
|
#--------------
|
|
all_features = gscv_fs.feature_names_in_
|
|
n_all_features = gscv_fs.n_features_in_
|
|
#all_features = gsfit.feature_names_in_
|
|
|
|
#--------------
|
|
# Selected features by the classifier
|
|
# Important to have var_type_colnames here
|
|
#----------------
|
|
#sel_features = X.columns[gscv_fs.best_estimator_.named_steps['fs'].get_support()] 3 only for numerical df
|
|
sel_features = var_type_colnames[gscv_fs.best_estimator_.named_steps['fs'].get_support()]
|
|
n_sf = gscv_fs.best_estimator_.named_steps['fs'].n_features_
|
|
|
|
#--------------
|
|
# Get model name
|
|
#--------------
|
|
model_name = gscv_fs.best_estimator_.named_steps['clf']
|
|
b_model_params = gscv_fs.best_params_
|
|
|
|
print('\n========================================'
|
|
, '\nRunning model:'
|
|
, '\nModel name:', model_name
|
|
, '\n==============================================='
|
|
, '\nRunning feature selection with RFECV for model'
|
|
, '\nTotal no. of features in model:', len(all_features)
|
|
, '\nThese are:\n', all_features, '\n\n'
|
|
, '\nNo of features for best model: ', n_sf
|
|
, '\nThese are:', sel_features, '\n\n'
|
|
, '\nBest Model hyperparams:', b_model_params
|
|
)
|
|
|
|
###########################################################################
|
|
############################## OUTPUT #####################################
|
|
###########################################################################
|
|
#=========================
|
|
# Blind test: BTS results
|
|
#=========================
|
|
# Build the final results with all scores for a feature selected model
|
|
#bts_predict = gscv_fs.predict(X_bts)
|
|
bts_predict = gscv_fs.predict(blind_test_df)
|
|
|
|
print('\nMCC on Blind test:' , round(matthews_corrcoef(blind_test_target, bts_predict),2))
|
|
print('\nAccuracy on Blind test:', round(accuracy_score(blind_test_target, bts_predict),2))
|
|
bts_mcc_score = round(matthews_corrcoef(blind_test_target, bts_predict),2)
|
|
|
|
# Diff b/w train and bts test scores
|
|
train_test_diff = train_bscore - bts_mcc_score
|
|
print('\nDiff b/w train and blind test score (MCC):', train_test_diff)
|
|
|
|
lr_btsD ={}
|
|
#lr_btsD['bts_mcc'] = bts_mcc_score
|
|
lr_btsD['bts_fscore'] = round(f1_score(blind_test_target, bts_predict),2)
|
|
lr_btsD['bts_precision'] = round(precision_score(blind_test_target, bts_predict),2)
|
|
lr_btsD['bts_recall'] = round(recall_score(blind_test_target, bts_predict),2)
|
|
lr_btsD['bts_accuracy'] = round(accuracy_score(blind_test_target, bts_predict),2)
|
|
lr_btsD['bts_roc_auc'] = round(roc_auc_score(blind_test_target, bts_predict),2)
|
|
lr_btsD['bts_jcc'] = round(jaccard_score(blind_test_target, bts_predict),2)
|
|
lr_btsD
|
|
|
|
#===========================
|
|
# Add FS related model info
|
|
#===========================
|
|
model_namef = str(model_name)
|
|
# FIXME: doesn't tell you which it has chosen
|
|
fs_methodf = str(gscv_fs.best_estimator_.named_steps['fs'])
|
|
all_featuresL = list(all_features)
|
|
fs_res_arrayf = str(list( gscv_fs.best_estimator_.named_steps['fs'].get_support()))
|
|
fs_res_array_rankf = str(list( gscv_fs.best_estimator_.named_steps['fs'].ranking_))
|
|
sel_featuresf = list(sel_features)
|
|
n_sf = int(n_sf)
|
|
|
|
output_modelD = {'model_name': model_namef
|
|
, 'model_refit_param': mod_refit_param
|
|
, 'Best_model_params': b_model_params
|
|
, 'n_all_features': n_all_features
|
|
, 'fs_method': fs_methodf
|
|
, 'fs_res_array': fs_res_arrayf
|
|
, 'fs_res_array_rank': fs_res_array_rankf
|
|
, 'all_feature_names': all_featuresL
|
|
, 'n_sel_features': n_sf
|
|
, 'sel_features_names': sel_featuresf}
|
|
#output_modelD
|
|
|
|
#========================================
|
|
# Update output_modelD with bts_results
|
|
#========================================
|
|
output_modelD.update(lr_btsD)
|
|
output_modelD
|
|
|
|
output_modelD['train_score (MCC)'] = train_bscore
|
|
output_modelD['bts_mcc'] = bts_mcc_score
|
|
output_modelD['train_bts_diff'] = round(train_test_diff,2)
|
|
print(output_modelD)
|
|
|
|
nlen = len(output_modelD)
|
|
|
|
#========================================
|
|
# Update output_modelD with cv_results
|
|
#========================================
|
|
output_modelD.update(cvD)
|
|
|
|
if (len(output_modelD) == nlen + len(cvD)):
|
|
print('\nFS run complete for model:', estimator
|
|
, '\nFS using:', fs
|
|
, '\nOutput dict size:', len(output_modelD))
|
|
return(output_modelD)
|
|
else:
|
|
sys.exit('\nFAIL:numbers mismatch output dict length not as expected. Please check')
|
|
|