-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathutils.py
More file actions
executable file
·230 lines (175 loc) · 7.98 KB
/
Copy pathutils.py
File metadata and controls
executable file
·230 lines (175 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
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
109
110
111
112
113
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
import pickle
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn.metrics import auc, recall_score, precision_recall_fscore_support, roc_auc_score
from src.utils_deepfri import load_FASTA
from deepgo2.deepgo.utils import Ontology
def load_pickle(filename):
file = open(filename, 'rb')
return pickle.load(file)
def update_scores(Y_pred, depth_fn, children_fn):
'''
The scores are updated per GO level starting
from the most distant terms to the root. This
guarantees that the scores are consistent with
the hierarchy.
The transformation has to be done by term:
score(x_il) = max(score(x_il), max(score(x_it), where t are the children of l))
"i" refers to the i-th gene.
'''
Y_pred_hier = Y_pred.copy()
terms_depth = np.load(depth_fn) # they are ordered like in all of the Y matrices
children_dict = load_pickle(children_fn) # dictionary with the terms as keys and their children as values
# The update of the predicted score has to be done from the most distant terms to the root (root is biological
# process, depth equal to 0)
indexes = np.argsort(terms_depth[:, 1].astype(int))[::-1]
ord_term = terms_depth[indexes, 0]
for protein in tqdm(range(Y_pred.shape[0]),leave=False):
scores_protein = Y_pred[protein]
for term in ord_term: # we do the update considering the ordered terms, from the most distant to the closest to the root
index_term = terms_depth[:, 0] == term
score_term = scores_protein[index_term]
children = children_dict[term]
if (len(children) > 0):
inte, ix, iy = np.intersect1d(children, terms_depth[:, 0], return_indices = True)
max_children = np.max(scores_protein[iy]) # finding the maximum score among the children's scores
if (max_children > score_term):
Y_pred_hier[protein, index_term] = max_children
return Y_pred_hier
def performance_assessment(Y_pred, Y_test, information_content, return_vals=False):
print('\nPerformance assessment')
sum_terms = Y_test.sum(axis = 0)
index_0 = sum_terms == 0
index_1 = sum_terms == Y_pred.shape[0]
index_keep = np.logical_not(np.logical_or(index_0, index_1))
################################## GENE CENTRIC MEASURES ####################################
# we obtain the recall, precision and f1-score per each protein (column) per threshold = t
# we threshold the label matrix
#thresholds = np.linspace(np.min(Y_pred), np.max(Y_pred), 100)
thresholds = np.linspace(0, 1, 100)
rec_prot, prec_prot, f_prot = [], [], []
precisions, recalls = np.array([]), np.array([])
precisionsm, recallsm =[], []
semantic_dist = []
for idx, t in tqdm(enumerate(thresholds),leave=False):
Y_pred_binary = (Y_pred > t).astype(int)
################ s_min #########################################
# Calculate false negatives and false positives
false_negatives = Y_test - Y_pred_binary
false_negatives[false_negatives == -1] = 0
false_positives = Y_pred_binary - Y_test
false_positives[false_positives == -1] = 0
# weighting and summing
ru_t = (1/len(Y_pred))*(false_negatives*information_content).sum()
mi_t = (1/len(Y_pred))*(false_positives*information_content).sum()
s_t = np.sqrt(ru_t**2 + mi_t**2)
semantic_dist.append(s_t)
################################################################
p, r, f, s = precision_recall_fscore_support( Y_test.T, Y_pred_binary.T, average=None, zero_division=1)
if ((Y_pred_binary.sum(axis = 1) > 0).sum() > 0):
p_av = np.mean(p[ Y_pred_binary.sum(axis = 1) > 0]) # following https://doi.org/10.1038/nmeth.2340,
# the precision per each threshold is obtained as the average
# across proteins having at least one prediction above threshold
else:
p_av = 0
r_av = np.mean(r) # the recall, instead, across all proteins.
# Saving results for threshold t
rec_prot.append(r_av)
prec_prot.append(np.mean(p))
if((p_av * r_av) == 0):
f_prot.append(0)
else:
f_prot.append(2*p_av * r_av/(p_av + r_av))
# macro term centric AUPRC
p, r, f, s = precision_recall_fscore_support( Y_test[:, index_keep], Y_pred_binary[:, index_keep], average=None, zero_division=1)
precisions = np.concatenate((precisions, p))
recalls = np.concatenate((recalls, r))
# micro
pm, rm, fm, sm = precision_recall_fscore_support(Y_test.flatten(), Y_pred_binary.flatten(),
average='binary', zero_division=1)
precisionsm.append(pm)
recallsm.append(rm)
print("-------------------------")
s_min = np.min(semantic_dist)
print('s_min: {}'.format(s_min))
F_max = np.max(f_prot)
print('-------------------------')
print('gene-centric F-max: {}'.format(F_max))
AUPRC_prot = auc(rec_prot, prec_prot)
print('gene-centric AUPRC: {}'.format(AUPRC_prot))
################################## TERM CENTRIC MEASURES ####################################
# area under the roc curve
auc_term = roc_auc_score(Y_test[:, index_keep], Y_pred[:, index_keep], average=None)
# term-centric area under the precision recall curve
precisions = precisions.reshape(len(thresholds), len(p))
recalls = recalls.reshape(len(thresholds), len(r))
auprc_term = []
for t in range(len(p)):
auprc_term.append(auc(recalls[:, t], precisions[:, t]))
micro = auc(recallsm, precisionsm)
# print('Term-centric average AUROC: {} +- {}'.format(np.mean(auc_term), np.std(auc_term)))
# print('-------------------------\n')
print('Term-centric average AUPRC: {} +- {}'.format(np.mean(auprc_term), np.std(auprc_term)))
# print('-------------------------\n')
print('Micro Term-centric average AUPRC: {}'.format(micro))
print('-------------------------\n')
if return_vals:
return (F_max, AUPRC_prot, np.mean(auprc_term), micro, s_min)
def performance_validation(Y_pred, Y_test):
print('\nPerformance assessment')
################################## GENE CENTRIC MEASURE ####################################
# we obtain the recall, precision and f1-score per each protein (column) per threshold = t
# we threshold the label matrix
#thresholds = np.linspace(np.min(Y_pred), np.max(Y_pred), 100)
thresholds = np.linspace(0, 1, 20)
rec_prot, prec_prot, f_prot = [], [], []
precisions, recalls = np.array([]), np.array([])
precisionsm, recallsm =[], []
for idx, t in tqdm(enumerate(thresholds),leave=False):
Y_pred_binary = (Y_pred > t).astype(int)
p, r, f, s = precision_recall_fscore_support(Y_test.T, Y_pred_binary.T, average=None, zero_division=0)
if ((Y_pred_binary.sum(axis = 1) > 0).sum() > 0):
p_av = np.mean(p[ Y_pred_binary.sum(axis = 1) > 0]) # following https://doi.org/10.1038/nmeth.2340,
# the precision per each threshold is obtained as the average
# across proteins having at least one prediction above threshold
else:
p_av = 0
r_av = np.mean(r) # the recall, instead, across all proteins.
# Saving results for threshold t
rec_prot.append(p_av)
prec_prot.append(r_av)
if((p_av * r_av) == 0):
f_prot.append(0)
else:
f_prot.append(2*p_av * r_av/(p_av + r_av))
################################# TERM CENTRIC MEASURE ####################################
pm, rm, fm, sm = precision_recall_fscore_support(Y_test.flatten(), Y_pred_binary.flatten(),
average='binary', zero_division=1)
precisionsm.append(pm)
recallsm.append(rm)
F_max = np.max(f_prot)
print('-------------------------')
print('gene-centric F-max: {}'.format(F_max))
micro = auc(recallsm, precisionsm)
print('Micro Term-centric average AUPRC: {}'.format(micro))
print('-------------------------\n')
return (F_max, micro)
def fasta_to_df(fn):
names,seq = load_FASTA(fn)
out_df = pd.DataFrame(data=seq,index=names,columns=['Sequence'])
# out_df = pd.DataFrame(columns=['Sequence'])
# with open(fn,'r') as f:
# lines = f.readlines()
# for gene in tqdm(range(0,len(lines),2),leave=False):
# out_df.loc[lines[gene].strip('>\n')] = lines[gene+1].strip('\n')
return out_df
def fasta_to_dict(fn):
names,seq = load_FASTA(fn)
out_dict = {k:v for k,v in zip(names,seq)}
# out_dict = {}
# with open(fn,'r') as f:
# lines = f.readlines()
# for gene in tqdm(range(0,len(lines),2),leave=False):
# out_dict[lines[gene].strip('>\n')] = lines[gene+1].strip('\n')
return out_dict