sklearn_rf_training_fixrank.py 13.1 KB
Newer Older
Marco Chierici's avatar
Marco Chierici committed
1
2
3
4
5
6
7
8
9
10
## 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
import csv
import os.path
from scaling import norm_l2
11
from mlpy import bootstrap_ci, borda_count, canberra_stability
Marco Chierici's avatar
Marco Chierici committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from input_output import load_data
import performance as perf
import sys
import tarfile
import glob
import argparse
import configparser as ConfigParser
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn import preprocessing
from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit, train_test_split

__author__  = 'Marco Chierici, Alessandro Zandona'
__version__ = '2.0'
__date__    = '15 December 2016'

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)')
#parser.add_argument('--plot', action='store_true', help='Plot metric values over all training cycles' )

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
#plot_out = args.plot
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]
SVM_TYPE = 'RandomForest'
OUTFILE = os.path.join(OUTDIR, '_'.join([BASEFILE, SVM_TYPE, 'RF' if RANK_METHOD=='randomForest' else RANK_METHOD]))

# 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
    OUTFILE = os.path.join(OUTDIR, '_'.join([BASEFILE, SVM_TYPE, RANK_METHOD + str(relief_k)]))
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)
y = np.loadtxt(LABELSFILE, dtype=np.int)
#print(var_names[:10])
# 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
109
110
111
112
113
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

# prepare output files
metricsf = open(OUTFILE + "_metrics.txt", 'w')
metrics_w = csv.writer(metricsf, delimiter='\t', lineterminator='\n')

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"])

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)
NPV = np.empty((CV_K*CV_N, len(FSTEPS)))
PPV = np.empty_like(NPV)
SENS = np.empty_like(NPV)
SPEC = np.empty_like(NPV)
MCC = np.empty_like(NPV)
AUC = np.empty_like(NPV)
DOR = np.empty_like(NPV)
ACC = np.empty_like(NPV)

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)


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

        #forest = RandomForestClassifier(n_estimators=500, criterion='gini')
        for j, s in enumerate(FSTEPS):
            #print j
            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)
            p = forest.predict(x_ts_fs)
            NPV[(n * CV_K) + i, j] = perf.npv(y_ts, p)
            PPV[(n * CV_K) + i, j] = perf.ppv(y_ts, p)
            SENS[(n * CV_K) + i, j] = perf.sensitivity(y_ts, p)
            SPEC[(n * CV_K) + i, j] = perf.specificity(y_ts, p)
            MCC[(n * CV_K) + i, j] = perf.KCCC_discrete(y_ts, p)
            AUC[(n * CV_K) + i, j] = roc_auc_score(y_ts, p)
            DOR[(n * CV_K) + i, j] = perf.dor(y_ts, p)
            ACC[(n * CV_K) + i, j] = perf.accuracy(y_ts, p)

# write metrics for all CV iterations
np.savetxt(OUTFILE + "_allmetrics_MCC.txt", MCC, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_SENS.txt", SENS, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_SPEC.txt", SPEC, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_PPV.txt", PPV, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_NPV.txt", NPV, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_AUC.txt", AUC, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_ACC.txt", ACC, fmt='%.4f', delimiter='\t')
np.savetxt(OUTFILE + "_allmetrics_DOR.txt", DOR, fmt='%.4f', delimiter='\t')

tar = tarfile.open(OUTFILE + "_allmetrics.tar.gz", "w:gz")
for metricFile in glob.glob(OUTFILE + "_allmetrics_*txt"):
    tar.add(metricFile, arcname=os.path.basename(metricFile))
    os.unlink(metricFile)
tar.close()

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

# average values
AMCC = np.mean(MCC, axis=0)
ASENS = np.mean(SENS, axis=0)
ASPEC = np.mean(SPEC, axis=0)
APPV = np.mean(PPV, axis=0)
ANPV = np.mean(NPV, axis=0)
AAUC = np.mean(AUC, axis=0)
AACC = np.mean(ACC, axis=0)
ADOR = np.mean(DOR, axis=0)
# approximated Odds Ratio, computed from ASENS and ASPEC (to avoid inf and nan values)
ADOR_APPROX = (ASENS / (1 - ASPEC)) / ((1 - ASENS) / ASPEC)

# confidence intervals
NPVCI = []
for i in range(NPV.shape[1]):
235
    NPVCI.append(bootstrap_ci(NPV[:, i]))
Marco Chierici's avatar
Marco Chierici committed
236
237
PPVCI = []
for i in range(PPV.shape[1]):
238
    PPVCI.append(bootstrap_ci(PPV[:, i]))
Marco Chierici's avatar
Marco Chierici committed
239
240
SENSCI = []
for i in range(SENS.shape[1]):
241
    SENSCI.append(bootstrap_ci(SENS[:, i]))
Marco Chierici's avatar
Marco Chierici committed
242
243
SPECCI = []
for i in range(SPEC.shape[1]):
244
    SPECCI.append(bootstrap_ci(SPEC[:, i]))
Marco Chierici's avatar
Marco Chierici committed
245
246
MCCCI = []
for i in range(MCC.shape[1]):
247
    MCCCI.append(bootstrap_ci(MCC[:, i]))
Marco Chierici's avatar
Marco Chierici committed
248
249
AUCCI = []
for i in range(AUC.shape[1]):
250
    AUCCI.append(bootstrap_ci(AUC[:, i]))
Marco Chierici's avatar
Marco Chierici committed
251
252
DORCI = []
for i in range(DOR.shape[1]):
253
    DORCI.append(bootstrap_ci(DOR[:, i]))
Marco Chierici's avatar
Marco Chierici committed
254
255
ACCCI = []
for i in range(ACC.shape[1]):
256
    ACCCI.append(bootstrap_ci(ACC[:, i]))
Marco Chierici's avatar
Marco Chierici committed
257
258

# Borda list
259
BORDA_ID, _, BORDA_POS = borda_count(RANKING)
Marco Chierici's avatar
Marco Chierici committed
260
261
262
263
264
265
266
# 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:
267
    STABILITY.append( canberra_stability(PR, ss) )
Marco Chierici's avatar
Marco Chierici committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347

metrics_w.writerow(["FS_WITH_BEST_MCC", opt_feats])
metrics_w.writerow(["STEP",
                    "MCC", "MCC_MIN", "MCC_MAX",
                    "SENS", "SENS_MIN", "SENS_MAX",
                    "SPEC", "SPEC_MIN", "SPEC_MAX",
                    "PPV", "PPV_MIN", "PPV_MAX",
                    "NPV", "NPV_MIN", "NPV_MAX",
                    "AUC", "AUC_MIN", "AUC_MAX",
                    "ACC", "ACC_MIN", "ACC_MAX",
                    "DOR", "DOR_MIN", "DOR_MAX",
                    "DOR_APPROX"])

stability_w.writerow(["STEP", "STABILITY"])

for j, s in enumerate(FSTEPS):
    metrics_w.writerow([s,
                        AMCC[j], MCCCI[j][0], MCCCI[j][1],
                        ASENS[j], SENSCI[j][0], SENSCI[j][1],
                        ASPEC[j], SPECCI[j][0], SPECCI[j][1],
                        APPV[j], PPVCI[j][0], PPVCI[j][1],
                        ANPV[j], NPVCI[j][0], NPVCI[j][1],
                        AAUC[j], AUCCI[j][0], AUCCI[j][1],
                        AACC[j], ACCCI[j][0], ACCCI[j][1],
                        ADOR[j], DORCI[j][0], DORCI[j][1],
                        ADOR_APPROX[j] ])
    stability_w.writerow( [s, STABILITY[j]] )

metricsf.close()
stabilityf.close()

for i, pos in zip(BORDA_ID, BORDA_POS):
    classes = np.unique(y)
    med_all = np.median(x[:, i])
    med_c = np.zeros(np.shape(classes)[0])
    for jj,c in enumerate(classes):
        med_c[jj] = np.median(x[y==c, i])
    with np.errstate(divide='ignore'):
        fc = med_c[1] / med_c[0]
    log2fc = np.log2(fc)
    ranking_w.writerow([ i, var_names[i], pos+1, med_all, med_c[0], med_c[1], fc, log2fc ])
rankingf.close()


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()


#if plot_out:
#    from metrics_plot import *
#    plt_title = (' ').join( [os.path.basename(DATAFILE).replace('.txt', ''), SVM_TYPE] )
#    if random_labels:
#        metplot(RLFile = (OUTFILE + "_metrics.txt"), title = plt_title)
#    elif RANK_METHOD=='random':
#        metplot(RRFile = (OUTFILE + "_metrics.txt"), title = plt_title)
#    else: 
#        metplot(normFile = (OUTFILE + "_metrics.txt"), title = plt_title)