280 lines
10 KiB
Python
Executable file
280 lines
10 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
Created on Wed Jun 29 19:44:06 2022
|
|
|
|
@author: tanu
|
|
"""
|
|
import sys, os
|
|
import pandas as pd
|
|
import numpy as np
|
|
import re
|
|
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
|
|
import itertools
|
|
from sklearn.model_selection import LeaveOneGroupOut
|
|
from boruta import BorutaPy
|
|
|
|
###############################################################################
|
|
# homedir = os.path.expanduser("~")
|
|
# sys.path.append(homedir + '/git/LSHTM_analysis/scripts/ml/ml_functions')
|
|
# sys.path
|
|
###############################################################################
|
|
#outdir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
|
|
|
|
#====================
|
|
# Import ML functions
|
|
#====================
|
|
#from ml_data_combined import *
|
|
#from MultClfs import *
|
|
#from GetMLData import *
|
|
#from SplitTTS import *
|
|
|
|
#skf_cv = StratifiedKFold(n_splits = 10 , shuffle = True, random_state = 42)
|
|
|
|
#logo = LeaveOneGroupOut()
|
|
|
|
########################################################################
|
|
# COMPLETE data: No tts_split
|
|
########################################################################
|
|
#%%
|
|
def CMLogoSkf_FS(cm_input_df
|
|
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
|
|
, bts_genes = ["embb", "katg", "rpob", "pnca", "gid"]
|
|
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
|
|
, target_var = 'dst_mode'
|
|
, gene_group = 'gene_name'
|
|
, std_gene_omit = []
|
|
, var_type = ['numerical', 'categorical','mixed']
|
|
|
|
):
|
|
|
|
n_jobs = os.cpu_count()
|
|
njobs = {'n_jobs': n_jobs }
|
|
rs = {'random_state': 42}
|
|
|
|
cm_gene_featuresD = {}
|
|
for bts_gene in bts_genes:
|
|
print('\n BTS gene:', bts_gene)
|
|
if not std_gene_omit:
|
|
training_genesL = ['alr']
|
|
else:
|
|
training_genesL = []
|
|
|
|
tr_gene_omit = std_gene_omit + [bts_gene]
|
|
n_tr_genes = (len(bts_genes) - (len(std_gene_omit)))
|
|
#n_total_genes = (len(bts_genes) - len(std_gene_omit))
|
|
n_total_genes = len(all_genes)
|
|
|
|
training_genesL = training_genesL + list(set(bts_genes) - set(tr_gene_omit))
|
|
#training_genesL = [element for element in bts_genes if element not in tr_gene_omit]
|
|
|
|
print('\nTotal genes: ', n_total_genes
|
|
,'\nTraining on:', n_tr_genes
|
|
,'\nTraining on genes:', training_genesL
|
|
, '\nOmitted genes:', tr_gene_omit
|
|
, '\nBlind test gene:', bts_gene)
|
|
|
|
print('\nDim of data:', cm_input_df.shape)
|
|
|
|
tts_split_type = "logo_skf_BT_" + bts_gene
|
|
|
|
#-------
|
|
# training
|
|
#------
|
|
cm_training_df = cm_input_df[~cm_input_df['gene_name'].isin(tr_gene_omit)]
|
|
|
|
cm_X = cm_training_df.drop(cols_to_drop, axis=1, inplace=False)
|
|
#cm_y = cm_training_df.loc[:,'dst_mode']
|
|
cm_y = cm_training_df.loc[:, target_var]
|
|
|
|
gene_group = cm_training_df.loc[:,'gene_name']
|
|
|
|
print('\nTraining data dim:', cm_X.shape
|
|
, '\nTraining Target dim:', cm_y.shape)
|
|
|
|
if all(cm_X.columns.isin(cols_to_drop) == False):
|
|
print('\nChecked training df does NOT have Target var')
|
|
else:
|
|
sys.exit('\nFAIL: training data contains Target var')
|
|
|
|
#---------------
|
|
# BTS: genes
|
|
#---------------
|
|
cm_test_df = cm_input_df[cm_input_df['gene_name'].isin([bts_gene])]
|
|
|
|
cm_bts_X = cm_test_df.drop(cols_to_drop, axis = 1, inplace = False)
|
|
#cm_bts_y = cm_test_df.loc[:, 'dst_mode']
|
|
cm_bts_y = cm_test_df.loc[:, target_var]
|
|
|
|
print('\nTEST data dim:' , cm_bts_X.shape
|
|
, '\nTEST Target dim:' , cm_bts_y.shape)
|
|
|
|
print("Running Multiple models on LOGO with SKF")
|
|
|
|
|
|
# REASSIGN for simplicity
|
|
# X
|
|
X_train = cm_X.copy()
|
|
X_test = cm_bts_X.copy()
|
|
X_train.shape
|
|
X_test.shape
|
|
|
|
# Y
|
|
y_train = cm_y.copy()
|
|
y_test = cm_bts_y.copy()
|
|
y_train.shape
|
|
y_test.shape
|
|
|
|
|
|
##############################################################################
|
|
#PREPROCESS
|
|
|
|
numerical_ix = X_train.select_dtypes(include=['int64', 'float64']).columns
|
|
numerical_ix
|
|
print("\nNo. of numerical indices:", len(numerical_ix))
|
|
|
|
categorical_ix = X_train.select_dtypes(include=['object', 'bool']).columns
|
|
categorical_ix
|
|
print("\nNo. of categorical indices:", len(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')
|
|
|
|
col_transform.fit(X_train)
|
|
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(X_train.columns)
|
|
, '\nNo. of columns post one hot encoder:', len(var_type_colnames))
|
|
else:
|
|
print('\nNo. of columns in input_df:', len(cm_input_df.columns))
|
|
|
|
|
|
##############################################################################
|
|
# FS: Random Forest + Boruta
|
|
|
|
X_train = col_transform.fit_transform(X_train)
|
|
X_test = col_transform.fit_transform(X_test)
|
|
|
|
fs_clf = "RandomForestClassifier"
|
|
rf_all_features = RandomForestClassifier(n_estimators=1000, max_depth=5
|
|
, **rs, **njobs)
|
|
|
|
# fit
|
|
rf_all_features.fit(np.array(X_train), np.array(y_train))
|
|
print("RF, baseline MCC:", matthews_corrcoef(y_test, rf_all_features.predict(X_test)))
|
|
|
|
# BORUTA and fit
|
|
boruta_selector = BorutaPy(rf_all_features,**rs, verbose = 3)
|
|
boruta_selector.fit(np.array(X_train), np.array(y_train))
|
|
|
|
# Get chosen features
|
|
print("Ranking: ", boruta_selector.ranking_)
|
|
print("No. of significant features: ", boruta_selector.n_features_)
|
|
|
|
|
|
X_important_train = boruta_selector.transform(np.array(X_train))
|
|
X_important_test = boruta_selector.transform(np.array(X_test))
|
|
|
|
# just retesting with selected features on RF itselfs
|
|
rf_all_features.fit(X_important_train, y_train)
|
|
print("RF, Boruta MCC:", matthews_corrcoef(y_test, rf_all_features.predict(X_important_test)))
|
|
|
|
selected_rf_features = pd.DataFrame({'Feature':list(var_type_colnames),
|
|
'Ranking':boruta_selector.ranking_})
|
|
|
|
sel_rf_features_sorted = selected_rf_features.sort_values(by='Ranking')
|
|
|
|
|
|
sel_features = var_type_colnames[boruta_selector.support_]
|
|
cm_gene_featuresD.update({bts_gene: {
|
|
"sel_features": sel_features
|
|
, "fs_ranking" : sel_rf_features_sorted
|
|
, "fs_model_name": fs_clf
|
|
}
|
|
}
|
|
)
|
|
|
|
|
|
return(cm_gene_featuresD)
|