modifying output dict for printing in UQ_FS_eg.py

This commit is contained in:
Tanushree Tunstall 2022-05-23 22:52:57 +01:00
parent 3c7d8690ee
commit 6db5046302

View file

@ -60,43 +60,51 @@ fs_bmod = clf2.best_estimator_
print('\nbest model with feature selection:', fs_bmod) print('\nbest model with feature selection:', fs_bmod)
######################################################### #########################################################
#cv = rskf_cv
cv = skf_cv
# my data: Feature Selelction + GridSearch CV + Pipeline # my data: Feature Selelction + GridSearch CV + Pipeline
pipe = Pipeline([ pipe = Pipeline([
('pre', MinMaxScaler()) ('pre', MinMaxScaler())
, ('fs', RFECV(LogisticRegression(**rs), cv = rskf_cv, scoring = 'matthews_corrcoef')) # , ('fs', RFECV(LogisticRegression(**rs), cv = cv, scoring = 'matthews_corrcoef'))
, ('fs', RFECV(DecisionTreeClassifier(**rs), cv = cv, scoring = 'matthews_corrcoef'))
, ('clf', LogisticRegression(**rs))]) , ('clf', LogisticRegression(**rs))])
search_space = [{'fs__min_features_to_select': [1,2] search_space = [
# ,'fs__cv': [rskf_cv] { 'fs__estimator': [LogisticRegression(**rs)]
}, , 'fs__min_features_to_select': [0,1]
{ ,'fs__cv': [rskf_cv]
#'clf': [LogisticRegression()], },
#'clf__C': np.logspace(0, 4, 10), {
'clf__C': [1], #'clf': [LogisticRegression()],
'clf__max_iter': [100], #'clf__C': np.logspace(0, 4, 10),
'clf__penalty': ['l1', 'l2'], 'clf__C': [1],
'clf__solver': ['saga'] 'clf__max_iter': [100],
}, 'clf__penalty': ['l1', 'l2'],
'clf__solver': ['saga']
},
{ {
#'clf': [LogisticRegression()], #'clf': [LogisticRegression()],
#'clf__C': np.logspace(0, 4, 10), #'clf__C': np.logspace(0, 4, 10),
'clf__C': [2, 2.5], 'clf__C': [2, 2.5],
'clf__max_iter': [100], 'clf__max_iter': [100],
'clf__penalty': ['l1', 'l2'], 'clf__penalty': ['l1', 'l2'],
'clf__solver': ['saga'] 'clf__solver': ['saga']
}, },
#{'clf': [RandomForestclf(n_estimators=100)],
# 'clf__max_depth': [5, 10, None]}, #{'clf': [RandomForestclf(n_estimators=100)],
#{'clf': [KNeighborsclf()], # 'clf__max_depth': [5, 10, None]},
# 'clf__n_neighbors': [3, 7, 11], #{'clf': [KNeighborsclf()],
# 'clf__weights': ['uniform', 'distance'] # 'clf__n_neighbors': [3, 7, 11],
#} # 'clf__weights': ['uniform', 'distance']
#}
] ]
gscv_fs = GridSearchCV(pipe gscv_fs = GridSearchCV(pipe
, search_space , search_space
, cv = rskf_cv , cv = cv
, scoring = mcc_score_fn , scoring = mcc_score_fn
, refit = 'mcc' , refit = 'mcc'
, verbose = 1 , verbose = 1
@ -111,14 +119,21 @@ gscv_fs.best_score_
# Training best score corresponds to the max of the mean_test<score> # Training best score corresponds to the max of the mean_test<score>
train_bscore = round(gscv_fs.best_score_, 2); train_bscore train_bscore = round(gscv_fs.best_score_, 2); train_bscore
print('\nTraining best score (MCC):', 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(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 # Training results
gscv_tr_resD = gscv_fs.cv_results_ gscv_tr_resD = gscv_fs.cv_results_
mod_refit_param = gscv_fs.refit mod_refit_param = gscv_fs.refit
# sanity check # sanity check
if train_bscore == round(gscv_tr_resD['mean_test_mcc'].max(),2): if train_bscore == check_train_score:
print('\nVerified training score (MCC):', train_bscore ) print('\nVerified training score (MCC):', train_bscore )
else: else:
print('\nTraining score could not be internatlly verified. Please check training results dict') print('\nTraining score could not be internatlly verified. Please check training results dict')
@ -186,19 +201,27 @@ print('\n========================================'
bts_predict = gscv_fs.predict(X_bts) bts_predict = gscv_fs.predict(X_bts)
print('\nMCC on Blind test:' , round(matthews_corrcoef(y_bts, bts_predict),2)) print('\nMCC on Blind test:' , round(matthews_corrcoef(y_bts, bts_predict),2))
print('\nAccuracy on Blind test:', round(accuracy_score(y_bts, bts_predict),2)) print('\nAccuracy on Blind test:', round(accuracy_score(y_bts, bts_predict),2))
bts_mcc_score = round(matthews_corrcoef(y_bts, bts_predict),2)
# Diff b/w train and bts test scores
train_test_diff = train_bscore - bts_mcc
print('\nDiff b/w train and blind test score (MCC):', train_test_diff)
# create a dict with all scores # create a dict with all scores
lr_btsD = {#'best_model': list(gscv_lr_fit_be_mod.items()) lr_btsD = {#'best_model': list(gscv_lr_fit_be_mod.items())
'bts_fscore':None #'bts_mcc':None
, 'bts_mcc':None 'bts_fscore':None
, 'bts_precision':None , 'bts_precision':None
, 'bts_recall':None , 'bts_recall':None
, 'bts_accuracy':None , 'bts_accuracy':None
, 'bts_roc_auc':None , 'bts_roc_auc':None
, 'bts_jaccard':None } , 'bts_jaccard':None}
lr_btsD lr_btsD
#lr_btsD['bts_mcc'] = bts_mcc_score
lr_btsD['bts_fscore'] = round(f1_score(y_bts, bts_predict),2) lr_btsD['bts_fscore'] = round(f1_score(y_bts, bts_predict),2)
lr_btsD['bts_mcc'] = round(matthews_corrcoef(y_bts, bts_predict),2)
lr_btsD['bts_precision'] = round(precision_score(y_bts, bts_predict),2) lr_btsD['bts_precision'] = round(precision_score(y_bts, bts_predict),2)
lr_btsD['bts_recall'] = round(recall_score(y_bts, bts_predict),2) lr_btsD['bts_recall'] = round(recall_score(y_bts, bts_predict),2)
lr_btsD['bts_accuracy'] = round(accuracy_score(y_bts, bts_predict),2) lr_btsD['bts_accuracy'] = round(accuracy_score(y_bts, bts_predict),2)
@ -218,8 +241,7 @@ output_modelD = {'model_name': model_name
, 'fs_res_array_rank': gscv_fs.best_estimator_.named_steps['fs'].ranking_ , 'fs_res_array_rank': gscv_fs.best_estimator_.named_steps['fs'].ranking_
, 'all_feature_names': all_features , 'all_feature_names': all_features
, 'n_sel_features': n_sf , 'n_sel_features': n_sf
, 'sel_features_names': sel_features , 'sel_features_names': sel_features}
, 'train_score (MCC)': train_bscore}
output_modelD output_modelD
#======================================== #========================================
@ -228,6 +250,12 @@ output_modelD
output_modelD.update(lr_btsD) output_modelD.update(lr_btsD)
output_modelD output_modelD
output_modelD['train_score (MCC)'] = train_bscore
output_modelD['bts_mcc'] = bts_mcc_score
output_modelD['train_bts_diff'] = train_test_diff
output_modelD
#======================================== #========================================
# Write final output file # Write final output file
# https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file # https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file