script to run models based on group of features
This commit is contained in:
parent
4ab99dcbd2
commit
905327bf4e
3 changed files with 1193 additions and 0 deletions
284
scripts/ml/MultModelsCl_dissected.py
Normal file
284
scripts/ml/MultModelsCl_dissected.py
Normal file
|
@ -0,0 +1,284 @@
|
|||
#!/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
|
||||
|
||||
#%% GLOBALS
|
||||
rs = {'random_state': 42}
|
||||
njobs = {'n_jobs': 10}
|
||||
|
||||
scoring_fn = ({ 'mcc' : make_scorer(matthews_corrcoef)
|
||||
, 'accuracy' : make_scorer(accuracy_score)
|
||||
, 'fscore' : make_scorer(f1_score)
|
||||
, 'precision' : make_scorer(precision_score)
|
||||
, 'recall' : make_scorer(recall_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)}
|
||||
#%%
|
||||
# Multiple Classification - Model Pipeline
|
||||
def MultModelsCl_dissected(input_df, target, skf_cv
|
||||
, blind_test_input_df
|
||||
, blind_test_target
|
||||
, var_type = ['numerical', 'categorical','mixed']):
|
||||
|
||||
'''
|
||||
@ 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 = [('Logistic Regression' , LogisticRegression(**rs) )
|
||||
, ('Logistic RegressionCV' , LogisticRegressionCV(**rs) )
|
||||
, ('Gaussian NB' , GaussianNB() )
|
||||
, ('Naive Bayes' , BernoulliNB() )
|
||||
# , ('K-Nearest Neighbors' , KNeighborsClassifier() )
|
||||
# , ('SVC' , SVC(**rs) )
|
||||
# , ('MLP' , MLPClassifier(max_iter = 500, **rs) )
|
||||
# , ('Decision Tree' , DecisionTreeClassifier(**rs) )
|
||||
# , ('Extra Trees' , ExtraTreesClassifier(**rs) )
|
||||
# , ('Extra Tree' , ExtraTreeClassifier(**rs) )
|
||||
# , ('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') )
|
||||
# , ('XGBoost' , XGBClassifier(**rs, verbosity = 0, use_label_encoder =False) )
|
||||
# , ('LDA' , LinearDiscriminantAnalysis() )
|
||||
# , ('Multinomial' , MultinomialNB() )
|
||||
# , ('Passive Aggresive' , PassiveAggressiveClassifier(**rs, **njobs) )
|
||||
# , ('Stochastic GDescent' , SGDClassifier(**rs, **njobs) )
|
||||
# , ('AdaBoost Classifier' , AdaBoostClassifier(**rs) )
|
||||
# , ('Bagging Classifier' , BaggingClassifier(**rs, **njobs, bootstrap = True, oob_score = True) )
|
||||
# , ('Gaussian Process' , GaussianProcessClassifier(**rs) )
|
||||
# , ('Gradient Boosting' , GradientBoostingClassifier(**rs) )
|
||||
# , ('QDA' , QuadraticDiscriminantAnalysis() )
|
||||
# , ('Ridge Classifier' , RidgeClassifier(**rs) )
|
||||
# , ('Ridge ClassifierCV' , RidgeClassifierCV(cv = 10) )
|
||||
]
|
||||
|
||||
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)
|
||||
|
||||
#----------
|
||||
# check 1
|
||||
#----------
|
||||
foo_df = pd.DataFrame.from_dict(skf_cv_modD, orient ='index')
|
||||
#foo_df = pd.DataFrame.from_dict(skf_cv_modD)
|
||||
|
||||
#===================
|
||||
# Confusion matrix: Not an easy problem to solve! STILL DOING it, 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
|
||||
#===================
|
||||
y_pred = cross_val_predict(model_pipeline, input_df, target, cv = 10, **njobs)
|
||||
#_tn, _fp, _fn, _tp = confusion_matrix(y_pred, y).ravel() # internally
|
||||
tn, fp, fn, tp = confusion_matrix(y_pred, target).ravel()
|
||||
# create a dict of confusion matrix that can be appended to the one above
|
||||
# cmD = {'TN' : np.array(tn)
|
||||
# , 'FP': np.array(fp)
|
||||
# , 'FN': np.array(fn)
|
||||
# , 'TP': np.array(tp)}
|
||||
|
||||
cmD = {'TN' : tn
|
||||
, 'FP': fp
|
||||
, 'FN': fn
|
||||
, 'TP': tp}
|
||||
skf_cv_modD.update(cmD)
|
||||
|
||||
#----------
|
||||
# check 2
|
||||
#----------
|
||||
#foo2_df = pd.DataFrame.from_dict(skf_cv_modD, orient ='index')
|
||||
#foo_df = pd.DataFrame.from_dict(skf_cv_modD)
|
||||
|
||||
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 a feature selected model
|
||||
#bts_predict = gscv_fs.predict(blind_test_input_df)
|
||||
model_pipeline.fit(input_df, target)
|
||||
bts_predict = model_pipeline.predict(blind_test_input_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)
|
||||
|
||||
|
||||
# # create a dict with all scores
|
||||
# lr_btsD = { 'model_name': model_name
|
||||
# , 'bts_mcc':None
|
||||
# , 'bts_fscore':None
|
||||
# , 'bts_precision':None
|
||||
# , 'bts_recall':None
|
||||
# , 'bts_accuracy':None
|
||||
# , 'bts_roc_auc':None
|
||||
# , 'bts_jaccard':None}
|
||||
|
||||
|
||||
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_jaccard'] = round(jaccard_score(blind_test_target, bts_predict),2)
|
||||
#mm_skf_scoresD[model_name]['diff_mcc'] = train_test_diff_MCC
|
||||
|
||||
return(mm_skf_scoresD)
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue