added combined model FS code and run script

This commit is contained in:
Tanushree Tunstall 2022-09-03 12:28:36 +01:00
parent 78704dec5a
commit 2b953583e2
7 changed files with 1046 additions and 0 deletions

View file

@ -0,0 +1,121 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 16:10:44 2022
@author: tanu
"""
from sklearn.ensemble import VotingClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, ExtraTreesClassifier
from boruta import BorutaPy
fooD = combined_DF_OS(combined_df)
numerical_ix = fooD['X'].select_dtypes(include=['int64', 'float64']).columns
numerical_ix
print("\nNo. of numerical indices:", len(numerical_ix))
categorical_ix = fooD['X'].select_dtypes(include=['object', 'bool']).columns
categorical_ix
print("\nNo. of categorical indices:", len(categorical_ix))
var_type = "mixed"
if var_type == 'mixed':
t = [('num', MinMaxScaler(), numerical_ix)
, ('cat', OneHotEncoder(), categorical_ix)]
col_transform = ColumnTransformer(transformers = t
, remainder='passthrough')
#--------------ALEX help
# col_transform
# col_transform.fit(X)
# test = col_transform.transform(X)
# print(col_transform.get_feature_names_out())
# foo = col_transform.fit_transform(X)
Xm_train = col_transform.fit_transform(fooD['X'])
fooD['X'].shape
Xm_train.shape
Xm_test = col_transform.fit_transform(fooD['X_bts'])
fooD['X_bts'].shape
Xm_test.shape
X_train = Xm_train.copy()
X_test = Xm_test.copy()
X_train.shape
X_test.shape
y_train = fooD['y']
y_test = fooD['y_bts']
y_train.shape
y_test.shape
# perhaps
#col_transform.fit(fooD['X'])
#encoded_colnames = pd.Index(col_transform.get_feature_names_out())
#======================
# 1 model
n_jobs = os.cpu_count()
njobs = {'n_jobs': n_jobs }
rs = {'random_state': 42}
rf_all_features = RandomForestClassifier(n_estimators=1000, max_depth=5
, **rs, **njobs)
#rf_all_features = VotingClassifier(estimators=1000)
rf_all_features = BaggingClassifier(random_state=1, n_estimators=100, verbose = 3, **njobs)
rf_all_features = AdaBoostClassifier(random_state=1, n_estimators=1000)
rf_all_features = ExtraTreesClassifier(random_state=1, n_estimators=1000, max_depth=5, verbose = 3)
rf_all_features = DecisionTreeClassifier(random_state=1, max_depth=5)
rf_all_features.fit(X_train, np.array(y_train))
accuracy_score(y_test, rf_all_features.predict(X_test))
matthews_corrcoef(y_test, rf_all_features.predict(X_test))
# BORUTA
boruta_selector = BorutaPy(rf_all_features,**rs, verbose = 3)
boruta_selector.fit(np.array(X_train), np.array(y_train))
# Tells you how many features: GOOD
print("Ranking: ", boruta_selector.ranking_)
print("No. of significant features: ", boruta_selector.n_features_)
cm_df = combined_df.drop(['gene_name', 'dst', 'dst_mode'], axis = 1)
col_transform.fit(cm_df)
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(cm_df.columns)
, '\nNo. of columns post one hot encoder:', len(var_type_colnames))
else:
print('\nNo. of columns in input_df:', len(input_df.columns))
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_]
# tells you the ranking: GOOD
#foo2 = selected_rf_features.sort_values(by='Ranking')
X_important_train = boruta_selector.transform(np.array(X_train))
X_important_test = boruta_selector.transform(np.array(X_test))
rf_all_features.fit(X_important_train, y_train)
accuracy_score(y_test, rf_all_features.predict(X_important_test))
matthews_corrcoef(y_test, rf_all_features.predict(X_important_test))

View file

@ -0,0 +1,280 @@
#!/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)

View file

@ -0,0 +1,32 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 3 09:43:22 2022
@author: tanu
"""
###############################################################################
homedir = os.path.expanduser("~")
sys.path.append(homedir + '/home/tanu/git/LSHTM_analysis/scripts/ml/combined_model')
sys.path.append(homedir + '/home/tanu/git/LSHTM_analysis/scripts/ml/ml_functions')
sys.path.append(homedir + '/home/tanu/git/LSHTM_analysis/scripts/ml')
from MultClfs import *
###############################################################################
#%% RUN: Combined model Baseline
outdir_cg = "/home/tanu/git/LSHTM_ML/output/combined/"
#===============
# Complete Data
#===============
CombinedModelML(cm_input_df = combined_df, outdir = outdir_cg, file_suffix = "complete")
CombinedModelML(cm_input_df = combined_df, outdir = outdir_cg, std_gene_omit=['alr'], file_suffix = "complete")
#===============
# Actual Data
#===============
CombinedModelML(cm_input_df = combined_df_actual, outdir = outdir_cg, file_suffix = "actual")
CombinedModelML(cm_input_df = combined_df_actual, outdir = outdir_cg, std_gene_omit=['alr'], file_suffix = "actual")

View file

@ -0,0 +1,204 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 19:17:46 2022
@author: tanu
"""
###############################################################################
homedir = os.path.expanduser("~")
sys.path.append(homedir + '/home/tanu/git/LSHTM_analysis/scripts/ml/combined_model')
sys.path.append(homedir + '/home/tanu/git/LSHTM_analysis/scripts/ml/ml_functions')
sys.path.append(homedir + '/home/tanu/git/LSHTM_analysis/scripts/ml')
from MultClfs import *
from cm_logo_skf_FS import *
###############################################################################
#%% FS with all genes in training
###############################################################################
# 1. Select Features
boruta_features = CMLogoSkf_FS(cm_input_df = combined_df,var_type = 'mixed', file_suffix = "complete")
# 2. Find original column names of features
# if it starts with num__, get rid of num__
# if it starts with cat__, get rid of cat__ and the _<number> at the end
for i in boruta_features:
print(i)
boruta_features[i]['sel_features']=[re.sub('^num__|cat__(.*)_\d*$',r'\1', current_thing) for current_thing in boruta_features[i]['sel_features']]
boruta_features[i]['sel_features'] = list(set(boruta_features[i]['sel_features']))
# write json
OutFile_6Tgenes = "/home/tanu/git/LSHTM_ML/output/feature_selection/boruta_features_6_Tgenes.json"
pd.DataFrame(boruta_features).to_json(path_or_buf=OutFile_6Tgenes)
# 3. Run all classification models using original column names from (2)
combined_df_embb=combined_df[boruta_features['embb']['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_katg=combined_df[boruta_features['katg']['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_pnca=combined_df[boruta_features['pnca']['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_gid= combined_df[boruta_features['gid' ]['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_rpob= combined_df[boruta_features['rpob' ]['sel_features']+['dst', 'dst_mode', 'gene_name']]
# from /home/tanu/git/LSHTM_analysis/scripts/ml/ml_functions/MultClf.py
CombinedModelML(combined_df_embb
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["embb"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = []
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS"
)
CombinedModelML(combined_df_katg
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["katg"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = []
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS"
)
CombinedModelML(combined_df_pnca
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["pnca"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = []
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS"
)
CombinedModelML(combined_df_gid
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["gid"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = []
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS"
)
CombinedModelML(combined_df_rpob
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["rpob"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = []
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS"
)
# write all feature rankings
for i in boruta_features:
print (i)
gene_fs_ranking = boruta_features[i]['fs_ranking']
gene_fs_ranking.to_csv("/home/tanu/git/LSHTM_ML/output/feature_selection/"+ i + "_boruta_featues_6Tgenes.csv")
###############################################################################
#%% FS withour training including ALR
###############################################################################
# With training omitting alr
boruta_features_omit_alr = CMLogoSkf_FS(cm_input_df = combined_df
, std_gene_omit = ['alr']
, var_type = 'mixed')
# 2. Find original column names of features
# if it starts with num__, get rid of num__
# if it starts with cat__, get rid of cat__ and the _<number> at the end
for i in boruta_features_omit_alr:
print(i)
boruta_features_omit_alr[i]['sel_features']=[re.sub('^num__|cat__(.*)_\d*$',r'\1', current_thing) for current_thing in boruta_features[i]['sel_features']]
boruta_features_omit_alr[i]['sel_features'] = list(set(boruta_features_omit_alr[i]['sel_features']))
# write json
OutFile_5Tgenes = "/home/tanu/git/LSHTM_ML/output/feature_selection/boruta_features_5_Tgenes.json"
pd.DataFrame(boruta_features_omit_alr).to_json(path_or_buf=OutFile_5Tgenes)
# 3. Run all classification models using original column names from (2)
cm_input_df5 = combined_df[~combined_df['gene_name'].isin(omit_gene_alr)]
combined_df_embb_no_alr = cm_input_df5[boruta_features_omit_alr['embb']['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_katg_no_alr = cm_input_df5[boruta_features_omit_alr['katg']['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_pnca_no_alr = cm_input_df5[boruta_features_omit_alr['pnca']['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_gid_no_alr = cm_input_df5[boruta_features_omit_alr['gid' ]['sel_features']+['dst', 'dst_mode', 'gene_name']]
combined_df_rpob_no_alr = cm_input_df5[boruta_features_omit_alr['rpob' ]['sel_features']+['dst', 'dst_mode', 'gene_name']]
CombinedModelML(combined_df_embb_no_alr
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["embb"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = ["alr"]
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS_no_Talr"
)
CombinedModelML(combined_df_katg_no_alr
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["katg"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = ["alr"]
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS_no_Talr"
)
CombinedModelML(combined_df_pnca_no_alr
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["pnca"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = ["alr"]
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS_no_Talr"
)
CombinedModelML(combined_df_gid_no_alr
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["gid"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = ["alr"]
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS_no_Talr"
)
CombinedModelML(combined_df_rpob_no_alr
, all_genes = ["embb", "katg", "rpob", "pnca", "gid", "alr"]
, bts_genes = ["rpob"]
, cols_to_drop = ['dst', 'dst_mode', 'gene_name']
, target_var = 'dst_mode'
, gene_group = 'gene_name'
, std_gene_omit = ["alr"]
, output_dir = "/home/tanu/git/LSHTM_ML/output/feature_selection/"
, file_suffix = "FS_no_Talr"
)
# write all feature rankings
for i in boruta_features_omit_alr:
print (i)
gene_fs_ranking_no_alr = boruta_features_omit_alr[i]['fs_ranking']
gene_fs_ranking_no_alr.to_csv("/home/tanu/git/LSHTM_ML/output/feature_selection/"+ i + "_boruta_featues_5Tgenes.csv")

52
scripts/ml/untitled5.py Normal file
View file

@ -0,0 +1,52 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 11:11:49 2022
@author: tanu
"""
# https://towardsdatascience.com/explain-feature-variation-employing-pca-in-scikit-learn-6711e0a5c0b7
from sklearn.decomposition import PCA
#import tensorflow as tf
#from tensorflow import keras
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.metrics import matthews_corrcoef
# pca = PCA().fit(X)
# plt.plot(np.cumsum(pca.explained_variance_ratio_))
# plt.xlabel(number of components)
# plt.ylabel(cumulative explained variance)
# from old scripts
fooD = combined_DF_OS(combined_df)
numerical_ix = fooD['X'].select_dtypes(include=['int64', 'float64']).columns
numerical_ix
num_featuresL = list(numerical_ix)
numerical_colind = fooD['X'].columns.get_indexer(list(numerical_ix) )
numerical_colind
numF = fooD['X'][numerical_ix]
categorical_ix = fooD['X'].select_dtypes(include=['object', 'bool']).columns
categorical_ix
categorical_colind = fooD['X'].columns.get_indexer(list(categorical_ix))
categorical_colind
##############
X_train,X_test,y_train,y_test=train_test_split(numF,fooD['y'],test_size=0.2)
pca=PCA(n_components=50)
X_train_new=pca.fit_transform(X_train)
X_test_new=pca.transform(X_test)
print(X_train.shape)
print(X_train_new.shape)
pca.explained_variance_ratio_
clf=KNeighborsClassifier(n_neighbors=5)
clf.fit(X_train_new,y_train)
y_pred_new=clf.predict(X_test_new)
matthews_corrcoef(y_test,y_pred_new)

136
scripts/ml/untitled6.py Normal file
View file

@ -0,0 +1,136 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 11:30:18 2022
@author: tanu
"""
#https://github.com/yuneeham/PCA-and-feature-selection_sklearn/blob/main/Report%20-%20PCA%20and%20Feature%20Selection.pdf
#Load Libraries
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn import datasets
from sklearn.preprocessing import scale
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
from sklearn.feature_selection import SelectFromModel
#Load Data
df = pd.read_csv("/home/tanu/Downloads/data.csv")
X = df.loc[:, ' ROA(C) before interest and depreciation before interest':' Equity to Liability'].values
y = df.loc[:,['Bankrupt?']].values
fn = df.loc[:, ' ROA(C) before interest and depreciation before interest':' Equity to Liability'].keys()
#Scaler/normalize
scaler = StandardScaler()
Xn = scaler.fit_transform(X)
#PCA
pca_prep = PCA().fit(Xn)
pca_prep.n_components_
#PCA Explained Variance
pca_prep.explained_variance_
plt.plot(pca_prep.explained_variance_ratio_)
#Graph plot - PCA components
plt.plot(pca_prep.explained_variance_ratio_)
plt.xlabel('k number of components')
plt.ylabel('Explained variance')
plt.grid(True)
plt.show()
#Number of components
n_pc = 17
pca = PCA(n_components = n_pc).fit(Xn)
Xp = pca.transform(Xn)
print(f'After PCA, we use {pca.n_components_} components. \n')
# Split the data into training and testing subsets.
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size =.2,random_state=1234,stratify=y)
Xp_train, Xp_test, yp_train, yp_test = train_test_split(Xp,y,test_size =.2,random_state=1234,stratify=y)
#Random Forest Model
rfcm = RandomForestClassifier().fit(X_train, y_train) #Original Data
rfcm_p = RandomForestClassifier().fit(Xp_train, yp_train) #Reduced Data
#Prediction
y_pred = rfcm.predict(X_test)
y_pred_p = rfcm_p.predict(Xp_test)
# Compare the performance of each mode
report_original = classification_report(y_test, y_pred)
report_pca = classification_report(yp_test, y_pred_p)
print(f'Classification Report - original\n{report_original}')
print(f'Classification Report - pca\n{report_pca}')
## Feature selection and performance comparison
# Draw a bar chart to see the sorted importance values with feature names.
# Horizontal Bar Chart
# %matplotlib auto
# %matplotlib inline
importances = rfcm.feature_importances_
np.sum(importances)
plt.barh(fn,importances)
df_importances = pd.DataFrame(data=importances, index=fn,
columns=['importance_value'])
df_importances.sort_values(by = 'importance_value', ascending=True,
inplace=True)
plt.barh(df_importances.index,df_importances.importance_value)
# Build a model with a subset of those features.
selector = SelectFromModel(estimator=RandomForestClassifier(),threshold=0.015)
X_reduced = selector.fit_transform(X,y)
selector.threshold_
selected_TF = selector.get_support()
print(f'\n** {selected_TF.sum()} features are selected.')
X_reduced.shape
# Show those selected features.
selected_features = []
for i,j in zip(selected_TF, fn):
if i: selected_features.append(j)
print(f'Selected Features: {selected_features}')
# First 5 features
print(selected_features[0:5])
# Build a model using those reduced number of features.
X_reduced_train, X_reduced_test, y_reduced_train, y_reduced_test \
= train_test_split(X_reduced,y,test_size =.3, stratify=y)
# Build a model with the reduced number of features.
rfcm2 = RandomForestClassifier().fit(X_reduced_train, y_reduced_train)
y_reduced_pred = rfcm2.predict(X_reduced_test)
#Classification for Reduced Data
print('\nClassification Report after feature reduction\n')
print(metrics.classification_report(y_reduced_test,y_reduced_pred))

View file

@ -0,0 +1,221 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 12:13:53 2022
@author: tanu
"""
# https://analyticsindiamag.com/hands-on-guide-to-automated-feature-selection-using-boruta/
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from boruta import BorutaPy
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import matthews_corrcoef
URL = "https://raw.githubusercontent.com/Aditya1001001/English-Premier-League/master/pos_modelling_data.csv"
data = pd.read_csv(URL)
data.info()
X = data.drop('Position', axis = 1)
y = data['Position']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .2, random_state = 1)
rf_all_features = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
rf_all_features.fit(X_train, y_train)
y_pred = rf_all_features.predict(X_test)
accuracy_score(y_test, rf_all_features.predict(X_test))
accuracy_score(y_test, y_pred)
matthews_corrcoef(y_test, rf_all_features.predict(X_test))
# BORUTA
rfc = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
boruta_selector = BorutaPy(rfc, n_estimators='auto', verbose=2, random_state=1)
boruta_selector.fit(np.array(X_train), np.array(y_train))
# Tells you how many features: GOOD
print("Ranking: ",boruta_selector.ranking_)
print("No. of significant features: ", boruta_selector.n_features_)
selected_rf_features = pd.DataFrame({'Feature':list(X_train.columns),
'Ranking':boruta_selector.ranking_})
# tells you the ranking: GOOD
selected_rf_features.sort_values(by='Ranking')
X_important_train = boruta_selector.transform(np.array(X_train))
X_important_test = boruta_selector.transform(np.array(X_test))
rf_boruta = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
rf_boruta.fit(X_important_train, y_train)
accuracy_score(y_test, rf_boruta.predict(X_important_test))
matthews_corrcoef(y_test, rf_boruta.predict(X_important_test))
##############################################################################
# my data : ONLY numerical values
# from old scripts (cm_logo_skf_v2.py)
fooD = combined_DF_OS(combined_df)
allF = fooD['X']
numerical_ix = fooD['X'].select_dtypes(include=['int64', 'float64']).columns
numerical_ix
# just numerical for X_train and X_test
X_train_numF = fooD['X'][numerical_ix]
X_test_numF = fooD['X_bts'][numerical_ix]
#X_train = allF
X_train = X_train_numF
X_test = X_test_numF
y_train = fooD['y']
y_test = fooD['y_bts']
# 1 model
rf_all_features = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
rf_all_features.fit(X_train, y_train)
accuracy_score(y_test, rf_all_features.predict(X_test))
matthews_corrcoef(y_test, rf_all_features.predict(X_test))
# BORUTA
rfc = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
boruta_selector = BorutaPy(rfc, n_estimators='auto', verbose=2, random_state=1)
boruta_selector.fit(np.array(X_train), np.array(y_train))
# Tells you how many features: GOOD
print("Ranking: ",boruta_selector.ranking_)
print("No. of significant features: ", boruta_selector.n_features_)
selected_rf_features = pd.DataFrame({'Feature':list(X_train.columns),
'Ranking':boruta_selector.ranking_})
# tells you the ranking: GOOD
selected_rf_features.sort_values(by='Ranking')
X_important_train = boruta_selector.transform(np.array(X_train))
X_important_test = boruta_selector.transform(np.array(X_test))
rf_boruta = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
rf_boruta.fit(X_important_train, y_train)
accuracy_score(y_test, rf_boruta.predict(X_important_test))
matthews_corrcoef(y_test, rf_boruta.predict(X_important_test))
##############################################################################
# my data : using both numerical and categorical
# from old scripts (cm_logo_skf_v2.py)
fooD = combined_DF_OS(combined_df)
numerical_ix = fooD['X'].select_dtypes(include=['int64', 'float64']).columns
numerical_ix
print("\nNo. of numerical indices:", len(numerical_ix))
categorical_ix = fooD['X'].select_dtypes(include=['object', 'bool']).columns
categorical_ix
print("\nNo. of categorical indices:", len(categorical_ix))
var_type = "mixeds"
if var_type == 'mixed':
t = [('num', MinMaxScaler(), numerical_ix)
, ('cat', OneHotEncoder(), categorical_ix)]
col_transform = ColumnTransformer(transformers = t
, remainder='passthrough')
#--------------ALEX help
# col_transform
# col_transform.fit(X)
# test = col_transform.transform(X)
# print(col_transform.get_feature_names_out())
# foo = col_transform.fit_transform(X)
Xm_train = col_transform.fit_transform(fooD['X'])
fooD['X'].shape
Xm_train.shape
Xm_test = col_transform.fit_transform(fooD['X_bts'])
fooD['X_bts'].shape
Xm_test.shape
X_train = Xm_train.copy()
X_test = Xm_test.copy()
X_train.shape
X_test.shape
y_train = fooD['y']
y_test = fooD['y_bts']
y_train.shape
y_test.shape
# perhaps
#col_transform.fit(fooD['X'])
#encoded_colnames = pd.Index(col_transform.get_feature_names_out())
#======================
# 1 model
rf_all_features = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
rf_all_features.fit(X_train, y_train)
accuracy_score(y_test, rf_all_features.predict(X_test))
matthews_corrcoef(y_test, rf_all_features.predict(X_test))
# BORUTA
rfc = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
boruta_selector = BorutaPy(rfc, n_estimators='auto', verbose=2, random_state=1)
boruta_selector.fit(np.array(X_train), np.array(y_train))
# Tells you how many features: GOOD
print("Ranking: ",boruta_selector.ranking_)
print("No. of significant features: ", boruta_selector.n_features_)
#selected_rf_features = pd.DataFrame({'Feature':list(X_train.columns),
# 'Ranking':boruta_selector.ranking_})
# tells you the ranking: GOOD
foo2 = selected_rf_features.sort_values(by='Ranking')
X_important_train = boruta_selector.transform(np.array(X_train))
X_important_test = boruta_selector.transform(np.array(X_test))
rf_boruta = RandomForestClassifier(random_state=1, n_estimators=1000, max_depth=5)
rf_boruta.fit(X_important_train, y_train)
accuracy_score(y_test, rf_boruta.predict(X_important_test))
matthews_corrcoef(y_test, rf_boruta.predict(X_important_test))
##################################
# trying to one hot encode at start
# perhaps
#col_transform.fit(fooD['X'])
#encoded_colnames = pd.Index(col_transform.get_feature_names_out())
# def encode_and_bind(original_dataframe, feature_to_encode):
# dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
# res = pd.concat([original_dataframe, dummies], axis=1)
# res = res.drop([feature_to_encode], axis=1)
# return(res)
# features_to_encode = ['feature_1', 'feature_2', 'feature_3',
# 'feature_4']
# features_to_encode = list(categorical_ix.copy())
# for feature in features_to_encode:
# X_train_enc = encode_and_bind(fooD['X'], feature)
# X_test_enc = encode_and_bind(fooD['X_bts'], feature)
# c1 = X_train_enc.columns
# c2 = X_test_enc.columns
# X_train_enc.shape
# X_test_enc.shape
# This one is better!
a = pd.get_dummies(combined_df, columns=features_to_encode)
a1=a.columns
a2 = a.drop(['gene_name', 'dst', 'dst_mode'])