added feature selection on all models but lets see if it works, only worked until DT

This commit is contained in:
Tanushree Tunstall 2022-05-23 07:47:56 +01:00
parent a420822a93
commit 3c7d8690ee
17 changed files with 2425 additions and 1202 deletions

View file

@ -12,78 +12,154 @@ Created on Tue Mar 15 11:09:50 2022
@author: tanu
"""
parameters = [
#cv = rskf_cv
cv = skf_cv
# LogisticRegression: Feature Selelction + GridSearch CV + Pipeline
###############################################################################
# Define estimator
estimator = LogisticRegression(**rs)
# Define pipleline with steps
pipe_lr = Pipeline([
('pre', MinMaxScaler())
, ('fs', RFECV(LogisticRegression(**rs), cv = rskf_cv, scoring = 'matthews_corrcoef'))
# , ('fs', RFECV(estimator, cv = cv, scoring = 'matthews_corrcoef'))
, ('clf', estimator)])
# Define hyperparmeter space to search for
param_grid_lr = [
{'fs__min_features_to_select' : [1,2]
# , 'fs__cv': [rskf_cv]
},
{
'clf': [LogisticRegression(**rs)],
#'clf__C': [0.001, 0.01, 0.1, 1, 10, 100, 1000],
# 'clf': [LogisticRegression(**rs)],
'clf__C': np.logspace(0, 4, 10),
'clf__penalty': ['none', 'l1', 'l2', 'elasticnet'],
'clf__max_iter': list(range(100,800,100)),
'clf__solver': ['saga']
},
{
'clf': [LogisticRegression(**rs)],
#'clf__C': [0.001, 0.01, 0.1, 1, 10, 100, 1000],
# 'clf': [LogisticRegression(**rs)],
'clf__C': np.logspace(0, 4, 10),
'clf__penalty': ['l2', 'none'],
'clf__max_iter': list(range(100,800,100)),
'clf__solver': ['newton-cg', 'lbfgs', 'sag']
},
{
'clf': [LogisticRegression(**rs)],
#'clf__C': [0.001, 0.01, 0.1, 1, 10, 100, 1000],
# 'clf': [LogisticRegression(**rs)],
'clf__C': np.logspace(0, 4, 10),
'clf__penalty': ['l1', 'l2'],
'clf__max_iter': list(range(100,800,100)),
'clf__solver': ['liblinear']
}
]
]
# Create pipeline
pipeline = Pipeline([
('pre', MinMaxScaler()),
('clf', ClfSwitcher()),
])
# Define GridSearch CV
gscv_fs = GridSearchCV(pipe_lr
, param_grid_lr
, cv = rskf_cv
, scoring = mcc_score_fn
, refit = 'mcc'
, verbose = 1
, return_train_score = True
, **njobs)
###############################################################################
#------------------------------
# Fit gscv containing pipeline
#------------------------------
gscv_fs.fit(X, y)
# Grid search i.e hyperparameter tuning and refitting on mcc
gscv_lr = GridSearchCV(pipeline
, parameters
#, scoring = 'f1', refit = 'f1'
, scoring = mcc_score_fn, refit = 'mcc'
, cv = skf_cv
, **njobs
, return_train_score = False
, verbose = 3)
#Fitting 10 folds for each of 4 candidates, totalling 80 fits
# QUESTION: HOW??
gscv_fs.best_params_
gscv_fs.best_score_
# Fit
gscv_lr_fit = gscv_lr.fit(X, y)
gscv_lr_fit_be_mod = gscv_lr_fit.best_params_
gscv_lr_fit_be_res = gscv_lr_fit.cv_results_
# 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)
round(gscv_fs.cv_results_['mean_test_mcc'].max(),2)
print('Best model:\n', gscv_lr_fit_be_mod)
print('Best models score:\n', gscv_lr_fit.best_score_, ':' , round(gscv_lr_fit.best_score_, 2))
# Training results
gscv_tr_resD = gscv_fs.cv_results_
mod_refit_param = gscv_fs.refit
#print('\nMean test score from fit results:', round(mean(gscv_lr_fit_be_res['mean_test_mcc']),2))
print('\nMean test score from fit results:', round(np.nanmean(gscv_lr_fit_be_res['mean_test_mcc']),2))
# sanity check
if train_bscore == round(gscv_tr_resD['mean_test_mcc'].max(),2):
print('\nVerified training score (MCC):', train_bscore )
else:
print('\nTraining score could not be internatlly verified. Please check training results dict')
# Blind test: REAL check!
tp = gscv_fs.predict(X_bts)
print('\nMCC on Blind test:' , round(matthews_corrcoef(y_bts, tp),2))
print('\nAccuracy on Blind test:', round(accuracy_score(y_bts, tp),2))
######################################
# Blind test
######################################
# See how it does on the BLIND test
#print('\nBlind test score, mcc:', ))
############
# info extraction
############
# gives input vals??
gscv_fs._check_n_features
test_predict = gscv_lr_fit.predict(X_bts)
print(test_predict)
print(np.array(y_bts))
y_btsf = np.array(y_bts)
# gives gscv params used
gscv_fs._get_param_names()
print(accuracy_score(y_bts, test_predict))
print(matthews_corrcoef(y_bts, test_predict))
# 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_
###############################################################################
#============
# FS results
#============
# Now get the features out
all_features = gscv_fs.feature_names_in_
n_all_features = gscv_fs.n_features_in_
#all_features = gsfit.feature_names_in_
sel_features = X.columns[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)
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))
# create a dict with all scores
lr_bts_dict = {#'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_precision':None
@ -91,46 +167,47 @@ lr_bts_dict = {#'best_model': list(gscv_lr_fit_be_mod.items())
, 'bts_accuracy':None
, 'bts_roc_auc':None
, 'bts_jaccard':None }
lr_bts_dict
lr_bts_dict['bts_fscore'] = round(f1_score(y_bts, test_predict),2)
lr_bts_dict['bts_mcc'] = round(matthews_corrcoef(y_bts, test_predict),2)
lr_bts_dict['bts_precision'] = round(precision_score(y_bts, test_predict),2)
lr_bts_dict['bts_recall'] = round(recall_score(y_bts, test_predict),2)
lr_bts_dict['bts_accuracy'] = round(accuracy_score(y_bts, test_predict),2)
lr_bts_dict['bts_roc_auc'] = round(roc_auc_score(y_bts, test_predict),2)
lr_bts_dict['bts_jaccard'] = round(jaccard_score(y_bts, test_predict),2)
lr_bts_dict
lr_btsD
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_recall'] = round(recall_score(y_bts, bts_predict),2)
lr_btsD['bts_accuracy'] = round(accuracy_score(y_bts, bts_predict),2)
lr_btsD['bts_roc_auc'] = round(roc_auc_score(y_bts, bts_predict),2)
lr_btsD['bts_jaccard'] = round(jaccard_score(y_bts, bts_predict),2)
lr_btsD
# Create a df from dict with all scores
lr_bts_df = pd.DataFrame.from_dict(lr_bts_dict,orient = 'index')
lr_bts_df.columns = ['Logistic_Regression']
print(lr_bts_df)
#===========================
# Add FS related model info
#===========================
output_modelD = {'model_name': model_name
, 'model_refit_param': mod_refit_param
, 'Best_model_params': b_model_params
, 'n_all_features': n_all_features
, 'fs_method': gscv_fs.best_estimator_.named_steps['fs'] # FIXME: doesn't tell you which it has chosen
, 'fs_res_array': gscv_fs.best_estimator_.named_steps['fs'].get_support()
, 'fs_res_array_rank': gscv_fs.best_estimator_.named_steps['fs'].ranking_
, 'all_feature_names': all_features
, 'n_sel_features': n_sf
, 'sel_features_names': sel_features
, 'train_score (MCC)': train_bscore}
output_modelD
# d2 = {'best_model_params': lis(gscv_lr_fit_be_mod.items() )}
# d2
# def Merge(dict1, dict2):
# res = {**dict1, **dict2}
# return res
# d3 = Merge(d2, lr_bts_dict)
# d3
#========================================
# Update output_modelD with bts_results
#========================================
output_modelD.update(lr_btsD)
output_modelD
# Create df with best model params
model_params = pd.Series(['best_model_params', list(gscv_lr_fit_be_mod.items() )])
model_params_df = model_params.to_frame()
model_params_df
model_params_df.columns = ['Logistic_Regression']
model_params_df.columns
#========================================
# Write final output file
# https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file
#========================================
# output final dict as a json
# outFile = 'LR_FS.json'
# with open(outFile, 'w') as f:
# json.dump(output_modelD, f)
# #
# with open(file, 'r') as f:
# data = json.load(f)
# Combine the df of scores and the best model params
lr_bts_df.columns
lr_output = pd.concat([model_params_df, lr_bts_df], axis = 0)
lr_output
# Format the combined df
# Drop the best_model_params row from lr_output
lr_df = lr_output.drop([0], axis = 0)
lr_df
#FIXME: tidy the index of the formatted df
###############################################################################