From 0c4f1e1e5ffce8073dabfb54560e3a3b53d2ecaf Mon Sep 17 00:00:00 2001 From: Tanushree Tunstall Date: Mon, 21 Mar 2022 13:51:20 +0000 Subject: [PATCH] added all classification algorithms params for gridsearch --- __pycache__/loopity_loop.cpython-37.pyc | Bin 4323 -> 4323 bytes classification_algo_names.py | 221 ++++++++++++++++++++++ hyperparams.py | 108 ++++++++++- hyperparams_p1.py | 238 +++++++++++++++--------- imports.py | 5 + intra_model_gscv.py | 26 ++- loopity_loop.py | 4 +- loopity_loop_CALL.py | 11 +- 8 files changed, 503 insertions(+), 110 deletions(-) diff --git a/__pycache__/loopity_loop.cpython-37.pyc b/__pycache__/loopity_loop.cpython-37.pyc index f1efd32f1fdfba334e5bcbbe9f04bfab4418c46e..994b92f60f0aecc06c7eb57c7f292c2cf036856e 100644 GIT binary patch delta 93 zcmaE?_*jwKiIl<&3u`EAeXr gNgsZ1#;D0N_!EHSPyTMv8lcvqDpaC+@=O6Q0M`y0e*gdg delta 93 zcmaE?_*jwKiI model may underfit +# Smaller value of K ==> the model may overfit. +#%%Support Vector Machine (SVM) +# example of grid searching key hyperparametres for SVC +from sklearn.datasets import make_blobs +from sklearn.model_selection import RepeatedStratifiedKFold +from sklearn.model_selection import GridSearchCV +from sklearn.svm import SVC +# define dataset +X, y = make_blobs(n_samples=1000, centers=2, n_features=100, cluster_std=20) +# define model and parameters +model = SVC() +kernel = ['poly', 'rbf', 'sigmoid'] +C = [50, 10, 1.0, 0.1, 0.01] +gamma = ['scale'] +# define grid search +grid = dict(kernel=kernel,C=C,gamma=gamma) +cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) +grid_search = GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, cv=cv, scoring='accuracy',error_score=0) +grid_result = grid_search.fit(X, y) +# summarize results +print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) +means = grid_result.cv_results_['mean_test_score'] +stds = grid_result.cv_results_['std_test_score'] +params = grid_result.cv_results_['params'] +for mean, stdev, param in zip(means, stds, params): + print("%f (%f) with: %r" % (mean, stdev, param)) + +# NOTES: +# https://stats.stackexchange.com/questions/31066/what-is-the-influence-of-c-in-svms-with-linear-kernel +# SVM terms: hyperplane, C and soft margins +# hyperplane that can min(max(dist)) of the suppor vectors from tne hyperplane +# High C ==> increase overfitting +# Low C ==> increase underfitting -scoring_refit_recall = {'scoring': 'recall' - ,'refit': 'recall'} +# But if C is a regularization parameter, why does a high C increase +# overfitting, when generally speaking regularization is done to +# mitigate overfitting, i.e., by creating a more general model? +# C is a regularisation parameter, but it is essentially attached to +# the data misfit term (the sum of the slack variables) rather than +# the regularisation term (the margin bit), so a larger value of C +# means less regularisation, rather than more. Alternatively you can +# view the usual representation of the rgularisation parameter +# as 1/C. -scoring_refit_recall = {'scoring': 'precision' - ,'refit': 'precision'} - -scoring_refit_mcc = {'scoring': mcc_score_fn - ,'refit': 'mcc'} -#n_jobs = 10 # my desktop has 12 cores -#cv = {'cv': 10}#%% - -njobs = {'n_jobs': 10} -skf_cv = StratifiedKFold(n_splits = 10, shuffle = True) - -#%% GSCV: RandomForest -gs_rf = GridSearchCV(estimator=RandomForestClassifier(n_jobs=-1, oob_score = True - #,class_weight = {1: 10/11, 0: 1/11} - ) - , param_grid=[{'max_depth': [4, 6, 8, 10, None] - , 'max_features': ['auto', 'sqrt'] - , 'min_samples_leaf': [2, 4, 8] - , 'min_samples_split': [10, 20]}] - , cv = skf_cv - , **njobs - , **scoring_refit_recall - #, **scoring_refit_mcc - #, scoring = scoring_fn, refit = False - ) -#gs_rf.fit(X_train, y_train) -#gs_rf_fit = gs_rf.fit(X_train y_train) - -gs_rf.fit(X, y) -gs_rf_fit = gs_rf.fit(X, y) -gs_rf_res = gs_rf_fit.cv_results_ -print('Best model:\n', gs_rf.best_params_) -print('Best models score:\n', gs_rf.best_score_) -print('Check mean models score:\n', mean(gs_rf_res['mean_test_score'])) - -#%% Proof of concept: manual inspection to see how best score is calcualted! -# SATISFIED! -# Best_model example: recall, Best model's score: 0.8059288537549408 -# {'max_depth': 4, 'max_features': 'sqrt', 'min_samples_leaf': 2, 'min_samples_split': 10} - -# Best model example: mcc, Best models score: 0.42504894661702863 -# {'max_depth': 4, 'max_features': 'auto', 'min_samples_leaf': 4, 'min_samples_split': 20} - -# Best model example: precision, Best models score: 0.7144745254745255 -# {'max_depth': 6, 'max_features': 'sqrt', 'min_samples_leaf': 8, 'min_samples_split': 10} - -best_model = [{'max_depth': 6, 'max_features': 'sqrt', 'min_samples_leaf': 8, 'min_samples_split': 10 }] - -gs_results_df = pd.DataFrame(gs_rf_res) -gs_results_df.shape - -gs_best_df = gs_results_df.loc[gs_results_df['params'].isin(best_model)] -gs_best_df.shape - -gs_best_df_test = gs_best_df.filter(like = 'test_', axis = 1) -gs_best_df_test.shape - -gs_best_df_test_recall = gs_best_df_test.filter(like = '_score', axis = 1) -gs_best_df_test_recall.shape - -f = gs_best_df_test_recall.filter(like='split', axis = 1) -f.shape -#gs_best_df_test_mcc = gs_best_df_test.filter(like = '_mcc', axis = 1) -#f = gs_best_df_test_mcc.filter(like='split', axis = 1) - -f.iloc[:,[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]].mean(axis = 1) -# recall: 0.801186 vs 0.8059288537549408 -# mcc: 0.425049 vs 0.42504894661702863 -# precision: 0.714475 vs 0.7144745254745255 - -#%% - -#%% Check the scores: -print([(len(train), len(test)) for train, test in skf_cv.split(X, y)]) -gs_rf_fit.cv_results_ -#its the weighted average!? -#%% +#C is a regularization parameter that controls the trade off +#between the achieving a low training error and a low testing +# error that is the ability to generalize your classifier to unseen data. +# C Parameter is used for controlling the outliers: +# low C implies ==> we are allowing more outliers +# high C implies we are allowing fewer outliers. diff --git a/imports.py b/imports.py index b5938a3..c6a2531 100644 --- a/imports.py +++ b/imports.py @@ -81,6 +81,11 @@ njobs = {'n_jobs': 10} skf_cv = StratifiedKFold(n_splits = 10 #, shuffle = False, random_state= None) , shuffle = True,**rs) +rskf_cv = RepeatedStratifiedKFold(n_splits = 10 + , n_repeats=3 + #, shuffle = False, random_state= None) + #, shuffle = True + ,**rs) #my_mcc = make_scorer({'mcc':make_scorer(matthews_corrcoef}) mcc_score_fn = {'mcc': make_scorer(matthews_corrcoef)} diff --git a/intra_model_gscv.py b/intra_model_gscv.py index 40ef39e..a4f905c 100644 --- a/intra_model_gscv.py +++ b/intra_model_gscv.py @@ -37,7 +37,7 @@ class ClfSwitcher(BaseEstimator): #def recall_score(self, X, y): # return self.estimator.recall_score(X, y) #%% Custom GridSearch: IntraModel[orig] -def grid_search2(input_df, target, skf_cv, var_type = ['numerical', 'categorical','mixed']) : +def grid_search(input_df, target, sel_cv, var_type = ['numerical', 'categorical','mixed']) : pipeline1 = Pipeline(( ('pre', MinMaxScaler()) @@ -73,7 +73,7 @@ def grid_search2(input_df, target, skf_cv, var_type = ['numerical', 'categorical for i in range(len(pars)): print('IIIII===>', i) gs = GridSearchCV(pips[i], pars[i] - , cv = skf_cv + , cv = sel_cv , **scoring_refit #, refit=False , **njobs @@ -82,9 +82,21 @@ def grid_search2(input_df, target, skf_cv, var_type = ['numerical', 'categorical print ("finished Gridsearch") print ('\nBest model:', gs.best_params_) print ('\nBest score:', gs.best_score_) -#%% Custom grid_search: Intra-Model [with return] +# TODO: add +# # summarize results +# print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) +# means = grid_result.cv_results_['mean_test_score'] +# stds = grid_result.cv_results_['std_test_score'] +# params = grid_result.cv_results_['params'] +# for mean, stdev, param in zip(means, stds, params): +# print("%f (%f) with: %r" % (mean, stdev, param)) + +# CALL: grid_search [orig] +grid_search() + +# #%% Custom grid_search: Intra-Model [with return] def grid_search(input_df, target - , skf_cv + , sel_cv , chosen_scoreD #scoring_refit #, var_type = ['numerical', 'categorical','mixed'] ): @@ -128,7 +140,7 @@ def grid_search(input_df, target print("\nStarting Gridsearch for model:", model_name, i) gs = GridSearchCV(all_pipelines[i], all_parameters[i] - , cv = skf_cv + , cv = sel_cv #, **scoring_refit #, refit=False , **chosen_scoreD @@ -150,6 +162,9 @@ def grid_search(input_df, target out[model_name].update(chosen_scoreD.copy()) out[model_name].update({'best_score': gs.best_score_}.copy()) return(out) + +# TODO: +# print, or see for each model mean test score and sd, sometimes they can be identical and your best model just picks one! #%% call CUSTOM grid_search: INTRA model [with return] # call chosen_score = {'scoring': 'recall' @@ -158,7 +173,6 @@ mcc_score_fn = {'chosen_scoreD': {'scoring': {'mcc': make_scorer(matthews_corrco ,'refit': 'mcc'} } } - intra_models = grid_search(X, y , skf_cv = skf_cv , chosen_scoreD= chosen_score diff --git a/loopity_loop.py b/loopity_loop.py index a0afc35..077ca66 100644 --- a/loopity_loop.py +++ b/loopity_loop.py @@ -40,7 +40,7 @@ njobs = {'n_jobs': 10} # TODO: get accuracy and other scores through K-fold cv # Multiple Classification - Model Pipeline -def MultClassPipeSKFLoop(input_df, target, skf_cv, var_type = ['numerical','categorical','mixed']): +def MultClassPipeSKFLoop(input_df, target, sel_cv, var_type = ['numerical','categorical','mixed']): ''' @ param input_df: input features @@ -131,7 +131,7 @@ def MultClassPipeSKFLoop(input_df, target, skf_cv, var_type = ['numerical','cate fold_dict.update({ model_name: {}}) #scores_df = pd.DataFrame() - for train_index, test_index in skf_cv.split(input_df, target): + for train_index, test_index in sel_cv.split(input_df, target): x_train_fold, x_test_fold = input_df.iloc[train_index], input_df.iloc[test_index] y_train_fold, y_test_fold = target.iloc[train_index], target.iloc[test_index] #print("Fold: ", fold_no, len(train_index), len(test_index)) diff --git a/loopity_loop_CALL.py b/loopity_loop_CALL.py index e70763e..e510a42 100644 --- a/loopity_loop_CALL.py +++ b/loopity_loop_CALL.py @@ -6,16 +6,17 @@ Created on Fri Mar 11 11:15:50 2022 @author: tanu """ #%% variables -rs = {'random_state': 42} +# rs = {'random_state': 42} -skf_cv = StratifiedKFold(n_splits = 10 - #, shuffle = False, random_state= None) - , shuffle = True,**rs) +# skf_cv = StratifiedKFold(n_splits = 10 +# #, shuffle = False, random_state= None) +# , shuffle = True,**rs) #%% MultClassPipeSKFLoop: function call() t3_res = MultClassPipeSKFLoop(input_df = num_df_wtgt[numerical_FN] , target = num_df_wtgt['mutation_class'] , var_type = 'numerical' - , skf_cv = skf_cv) + , sel_cv = skf_cv) + #, sel_cv = rskf_cv) pp.pprint(t3_res) #print(t3_res) ################################################################