sklearn_rf_training_fixrank.py 11.7 KB
Newer Older
Marco Chierici's avatar
Marco Chierici committed
1
2
3
4
5
6
7
## This code is written by Marco Chierici <chierici@fbk.eu>, Alessandro Zandona' <zandona@fbk.eu>.
## Based on code previously written by Davide Albanese.

## Requires Python >= 2.7, mlpy >= 3.5


import numpy as np
8
import pandas as pd
Marco Chierici's avatar
Marco Chierici committed
9
10
import csv
import os.path
11
from mlpy import borda_count, canberra_stability
Marco Chierici's avatar
Marco Chierici committed
12
13
14
15
16
17
18
from input_output import load_data
import performance as perf
import sys
import glob
import argparse
import configparser as ConfigParser
from sklearn.ensemble import RandomForestClassifier
19
from sklearn.multiclass import OneVsRestClassifier
20
from sklearn.metrics import roc_auc_score, matthews_corrcoef, accuracy_score
Marco Chierici's avatar
Marco Chierici committed
21
22
from sklearn import preprocessing
from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit, train_test_split
23
24
import bootstrapped.bootstrap as bs
import bootstrapped.stats_functions as bs_stats
Marco Chierici's avatar
Marco Chierici committed
25

26
27
28
__author__  = 'Marco Chierici'
__version__ = '2.5'
__date__    = '28 Nov 2019'
Marco Chierici's avatar
Marco Chierici committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

class myArgumentParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwargs):
        super(myArgumentParser, self).__init__(*args, **kwargs)

    def convert_arg_line_to_args(self, line):
        for arg in line.split():
            if not arg.strip():
                continue
            if arg[0] == '#':
                break
            yield arg

parser = myArgumentParser(description='Run a training experiment (10x5-CV fold) using Random Forest as classifier.',
        fromfile_prefix_chars='@')
parser.add_argument('DATAFILE', type=str, help='Training datafile')
parser.add_argument('LABELSFILE', type=str, help='Sample labels')
parser.add_argument('OUTDIR', type=str, help='Output directory')
parser.add_argument('--ranking', dest='RANK_METHOD', type=str, choices=['ReliefF', 'tree', 'randomForest', 'KBest', 'random', 'rankList'], default='randomForest', help='Feature ranking method: ReliefF, extraTrees, Random Forest, Anova F-score, random ranking, external ranked features list (default: %(default)s)')
parser.add_argument('--random', action='store_true', help='Run with random sample labels')
parser.add_argument('--cv_k', type=np.int, default=5, help='Number of CV folds (default: %(default)s)')
parser.add_argument('--cv_n', type=np.int, default=10, help='Number of CV cycles (default: %(default)s)')
parser.add_argument('--rankFeats', type=str, default='', help='Ranked features list to be used by Machine Learning [Feats name on 1st column, feats weights on 2nd column, with HEADER]')
parser.add_argument('--reliefk', type=np.int, default=3, help='Number of nearest neighbors for ReliefF (default: %(default)s)')

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)

args = parser.parse_args()
DATAFILE = args.DATAFILE
LABELSFILE = args.LABELSFILE
RANK_METHOD = args.RANK_METHOD
OUTDIR = args.OUTDIR
random_labels = args.random
CV_K = args.cv_k
CV_N = args.cv_n
RANKFEATS = args.rankFeats
relief_k = args.reliefk

BASEFILE = os.path.splitext(os.path.basename(DATAFILE))[0]
70
71
MODEL_TYPE = 'RandomForest'
OUTFILE = os.path.join(OUTDIR, '_'.join([BASEFILE, MODEL_TYPE, 'RF' if RANK_METHOD=='randomForest' else RANK_METHOD]))
Marco Chierici's avatar
Marco Chierici committed
72
73
74
75
76
77
78
79
80
81
82
83

# create OUTDIR if not present
try:
    os.makedirs(OUTDIR)
except OSError:
    if not os.path.isdir(OUTDIR):
        raise

# load modules
if RANK_METHOD == 'ReliefF':
    from relief import ReliefF
    # add ReliefF K to OUTFILE
84
    OUTFILE = os.path.join(OUTDIR, '_'.join([BASEFILE, MODEL_TYPE, RANK_METHOD + str(relief_k)]))
Marco Chierici's avatar
Marco Chierici committed
85
86
87
88
89
90
91
92
93
94
95
elif RANK_METHOD == 'tree' :
    from sklearn.ensemble import ExtraTreesClassifier
elif RANK_METHOD == 'KBest':
    from sklearn.feature_selection import SelectKBest, f_classif

# number of Montecarlo CV cycles (for SVM tuning)
TUN_CV_K = 10
# fraction of the dataset to keep apart as test split (for SVM tuning)
TUN_CV_P = 50

sample_names, var_names, x = load_data(DATAFILE)
96
97
98
99
100
y_orig = np.loadtxt(LABELSFILE, dtype=np.int)
# encode labels
le = preprocessing.LabelEncoder()
y = le.fit_transform(y_orig)

Marco Chierici's avatar
Marco Chierici committed
101
102
103
104
105
106
107
108
109
110
111
# If ranked list is given as input to DAP, read it and extract features index
if RANK_METHOD == "rankList":
    rankedList = np.loadtxt(RANKFEATS, delimiter='\t', dtype=str, skiprows=1)
    ranked_feats = rankedList[:,0]
    # Find index of features inside dataset
    ranked_feats_idx = []
    for el in ranked_feats.tolist():
        ranked_feats_idx.append(np.where([el==vn for vn in var_names])[0][0])

# build FSTEPS according to dataset size
nfeat = x.shape[1]
Marco Chierici's avatar
Marco Chierici committed
112
113
114
115
116
feature_ranges = [5, 10, 25, 50, 75, 100]
FSTEPS = list()
for percentage in feature_ranges:
    k = np.ceil((nfeat * percentage) / 100).astype(np.int)
    FSTEPS.append(k)
Marco Chierici's avatar
Marco Chierici committed
117
118

# prepare output files
119
120
121
#rankingf = open(OUTFILE + "_featurelist.txt", 'w')
#ranking_w = csv.writer(rankingf, delimiter='\t', lineterminator='\n')
#ranking_w.writerow(["FEATURE_ID", "FEATURE_NAME", "MEAN_POS", "MEDIAN_ALL", "MEDIAN_0", "MEDIAN_1", "FOLD_CHANGE", "LOG2_FOLD_CHANGE"])
Marco Chierici's avatar
Marco Chierici committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

stabilityf = open(OUTFILE + "_stability.txt", 'w')
stability_w = csv.writer(stabilityf, delimiter='\t', lineterminator='\n')

# prepare output arrays
RANKING = np.empty((CV_K*CV_N, x.shape[1]), dtype=np.int)

ys=[]

if random_labels:
    np.random.seed(0)
    tmp = y.copy()
    np.random.shuffle(tmp)
    for i in range(CV_N):
        ys.append(tmp)
else:
    for i in range(CV_N):
        ys.append(y)

141
cvmetrics_df = pd.DataFrame(columns=['Iteration', 'Fold', 'nf', 'mcc', 'sens', 'spec', 'acc', 'auc', 'npv', 'ppv'])
Marco Chierici's avatar
Marco Chierici committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

for n in range(CV_N):
    skf = StratifiedKFold(CV_K, shuffle=True, random_state=n)

    for i, (idx_tr, idx_ts) in enumerate(skf.split(x, ys[n])):

        x_tr, x_ts = x[idx_tr], x[idx_ts]
        y_tr, y_ts = ys[n][idx_tr], ys[n][idx_ts]

        forest = RandomForestClassifier(n_estimators=500, criterion='gini', random_state=n, n_jobs=1)
        forest.fit(x_tr, y_tr)
        
        if RANK_METHOD == 'random':
            ranking_tmp = np.arange(len(var_names))
            np.random.seed((n*CV_K)+i)
            np.random.shuffle(ranking_tmp)
        elif RANK_METHOD == 'ReliefF':
            relief = ReliefF(relief_k, seed=n)
            relief.learn(x_tr, y_tr)
            w = relief.w()
            ranking_tmp = np.argsort(w)[::-1]
        elif RANK_METHOD == 'tree' :
            forest = ExtraTreesClassifier(n_estimators=250, criterion='gini', random_state=n)
            forest.fit(x_tr, y_tr)
            ranking_tmp = np.argsort(forest.feature_importances_)[::-1]
        elif RANK_METHOD == 'randomForest' :
            ranking_tmp = np.argsort(forest.feature_importances_)[::-1]
        elif RANK_METHOD == 'KBest':
            selector = SelectKBest(f_classif)
            selector.fit(x_tr, y_tr)
            ranking_tmp = np.argsort( -np.log10(selector.pvalues_) )[::-1]
        elif RANK_METHOD == 'rankList':
            ranking_tmp = ranked_feats_idx 
                       
        RANKING[(n * CV_K) + i] = ranking_tmp

        for j, s in enumerate(FSTEPS):
            v = RANKING[(n * CV_K) + i][:s]
            x_tr_fs, x_ts_fs = x_tr[:, v], x_ts[:, v]
            forest.fit(x_tr_fs, y_tr)
182
183
184
185
186
187
188
189
190
191
192
193
194
195
            yp = forest.predict(x_ts_fs)

            cvmetrics_df = cvmetrics_df.append({'Iteration': n, 'Fold': i, 'nf': s, 
                'mcc': matthews_corrcoef(y_ts, yp),
                'sens': perf.sensitivity(y_ts, yp),
                'spec': perf.specificity(y_ts, yp),
                'acc': accuracy_score(y_ts, yp),
                'auc': roc_auc_score(y_ts, yp),
                'npv': perf.npv(y_ts, yp),
                'ppv': perf.ppv(y_ts, yp)}, ignore_index=True)


cvmetrics_df[['Iteration', 'Fold', 'nf']] = cvmetrics_df[['Iteration', 'Fold', 'nf']].astype(int)
cvmetrics_df.to_csv(f"{OUTFILE}_allmetrics.txt", sep='\t', index=False, float_format="%.3f")
Marco Chierici's avatar
Marco Chierici committed
196
197
198
199
200

# write all rankings
np.savetxt(OUTFILE + "_ranking.csv.gz", RANKING, fmt='%d', delimiter='\t')

# average values
201
avg_df = cvmetrics_df.groupby(['nf']).mean()
Marco Chierici's avatar
Marco Chierici committed
202
203

# confidence intervals
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
AMCC, ASENS, ASPEC, AACC, AAUC, ANPV, APPV = [avg_df[metric].values for metric in ['mcc', 'sens', 'spec', 'acc', 'auc', 'npv', 'ppv']]
MCC_CI, SENS_CI, SPEC_CI, ACC_CI, AUC_CI, NPV_CI, PPV_CI = ([] for i in range(7))
for nf in FSTEPS:
    res = bs.bootstrap(cvmetrics_df['mcc'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    MCC_CI.append([res.lower_bound, res.upper_bound])
    res = bs.bootstrap(cvmetrics_df['sens'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    SENS_CI.append([res.lower_bound, res.upper_bound])
    res = bs.bootstrap(cvmetrics_df['spec'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    SPEC_CI.append([res.lower_bound, res.upper_bound])
    res = bs.bootstrap(cvmetrics_df['acc'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    ACC_CI.append([res.lower_bound, res.upper_bound])
    res = bs.bootstrap(cvmetrics_df['auc'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    AUC_CI.append([res.lower_bound, res.upper_bound])
    res = bs.bootstrap(cvmetrics_df['npv'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    NPV_CI.append([res.lower_bound, res.upper_bound])
    res = bs.bootstrap(cvmetrics_df['ppv'][cvmetrics_df['nf']==nf].values, stat_func=bs_stats.mean)
    PPV_CI.append([res.lower_bound, res.upper_bound])
Marco Chierici's avatar
Marco Chierici committed
221
222

# Borda list
223
BORDA_ID, _, BORDA_POS = borda_count(RANKING)
Marco Chierici's avatar
Marco Chierici committed
224
225
226
227
228
229
230
# optimal number of features (yielding max MCC)
opt_feats = FSTEPS[np.argmax(AMCC)]

# Canberra stability indicator
STABILITY = []
PR = np.argsort( RANKING )
for ss in FSTEPS:
231
    STABILITY.append( canberra_stability(PR, ss) )
Marco Chierici's avatar
Marco Chierici committed
232

233
234
235
236
237
238
239
240
241
metrics_array = np.empty((len(FSTEPS), 22))
for j,s in enumerate(FSTEPS):
    metrics_array[j] = np.array([s, AMCC[j], MCC_CI[j][0], MCC_CI[j][1], ASENS[j], SENS_CI[j][0], SENS_CI[j][1], 
    ASPEC[j], SPEC_CI[j][0], SPEC_CI[j][1], AACC[j], ACC_CI[j][0], ACC_CI[j][1],
    AAUC[j], AUC_CI[j][0], AUC_CI[j][1], ANPV[j], NPV_CI[j][0], NPV_CI[j][1],
    APPV[j], PPV_CI[j][0], PPV_CI[j][1]])
metrics_df = pd.DataFrame(metrics_array, columns=["nf", "mcc", "mcc_min", "mcc_max", "sens", "sens_min", "sens_max", "spec", "spec_min", "spec_max", "acc", "acc_min", "acc_max", "auc", "auc_min", "auc_max", "npv", "npv_min", "npv_max", "ppv", "ppv_min", "ppv_max"])
metrics_df['nf'] = metrics_df['nf'].astype(int)
metrics_df.to_csv(f"{OUTFILE}_metrics.txt", sep='\t', index=False, float_format="%.3f")
Marco Chierici's avatar
Marco Chierici committed
242
243
244
245
246
247
248

stability_w.writerow(["STEP", "STABILITY"])
for j, s in enumerate(FSTEPS):
    stability_w.writerow( [s, STABILITY[j]] )

stabilityf.close()

249
250
251
borda_array = np.empty((len(BORDA_ID), 3))
borda_df = pd.DataFrame(columns=["FEATURE_ID", "FEATURE_NAME", "MEAN_POS"])

Marco Chierici's avatar
Marco Chierici committed
252
for i, pos in zip(BORDA_ID, BORDA_POS):
253
    borda_df = borda_df.append({'FEATURE_ID': i, 'FEATURE_NAME': var_names[i], 'MEAN_POS': pos+1}, ignore_index=True)
Marco Chierici's avatar
Marco Chierici committed
254

255
borda_df.to_csv(f"{OUTFILE}_featurelist.txt", sep='\t', index=False, float_format="%.3f")
Marco Chierici's avatar
Marco Chierici committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

logf = open(OUTFILE + ".log", 'w')
config = ConfigParser.RawConfigParser()
config.add_section("SOFTWARE VERSIONS")
config.set("SOFTWARE VERSIONS", os.path.basename(__file__), __version__)
config.set("SOFTWARE VERSIONS", "Python", sys.version.replace('\n', ''))
config.set("SOFTWARE VERSIONS", "Numpy", np.__version__)
config.add_section("CV PARAMETERS")
config.set("CV PARAMETERS", "Folds", CV_K)
config.set("CV PARAMETERS", "Iterations", CV_N)
config.add_section("INPUT")
config.set("INPUT", "Data", os.path.realpath( DATAFILE ))
config.set("INPUT", "Labels", os.path.realpath( LABELSFILE ))
config.set("INPUT", "Classifier", "RandomForest")
config.set("INPUT", "n_estimators", 500)
config.set("INPUT", "Rank_method", RANK_METHOD)
config.set("INPUT", "Random_labels", random_labels)
config.add_section("OUTPUT")
config.set("OUTPUT", "Metrics", os.path.realpath( OUTFILE + "_metrics.txt" ))
config.set("OUTPUT", "Borda", os.path.realpath( OUTFILE + "_featurelist.txt" ))
config.set("OUTPUT", "Internal", os.path.realpath( OUTFILE + "_internal.txt" ))
config.set("OUTPUT", "Stability", os.path.realpath( OUTFILE + "_stability.txt" ))
config.set("OUTPUT", "MCC", np.max(AMCC))
config.set("OUTPUT", "N_feats", opt_feats)
config.write(logf)
logf.close()