-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSKLClassifier.py
245 lines (210 loc) · 10.2 KB
/
SKLClassifier.py
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import collections
import gc
import logging
import random
from tqdm import tqdm
import numpy as np
from sklearn import neural_network, ensemble
from sklearn.metrics import PrecisionRecallDisplay, confusion_matrix, RocCurveDisplay, ConfusionMatrixDisplay
from imblearn.over_sampling import BorderlineSMOTE, RandomOverSampler, SMOTE
from imblearn.under_sampling import TomekLinks, NeighbourhoodCleaningRule
import joblib
import ToxProtParse
import pickle
import matplotlib.pyplot as plt
import pandas as pd
from xgboost import XGBClassifier, XGBRFClassifier
plt.rcParams.update({'font.size': 18})
random.seed(123)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def lmap(imp,cut):
if imp>cut:
return 1
else:
return 0
###Training
"""with open("100_train_embedded.pickle","rb") as tp:
training_data = pickle.load(tp)
#with open("100_test_embedded.pickle", "rb") as td:
# test_data = pickle.load(td)
# training_data[0]=np.concatenate((training_data[0], test_data[0]))
# training_data[1]=np.concatenate((training_data[1], test_data[1]))
print("Training started")
model = neural_network.MLPClassifier(solver="adam", verbose=True, early_stopping=True,
hidden_layer_sizes=(500, 250), alpha=1e-8, tol=0.0001)
model.fit(training_data[0], training_data[1])
joblib.dump(model, "MLP_default_100.joblib")
print("Training ended")
del training_data
gc.collect()"""
###Testing
"""with open("ToxPredN.pickle", "rb") as tp:
test_data: list = pickle.load(tp)
with open("ToxPredP.pickle", "rb") as tp:
test_data2 = pickle.load(tp)
test_data[0] += test_data2[0]
test_data[1] = np.concatenate((test_data[1], test_data2[1]))
test_data[2] += test_data2[2]"""
###OR"""
"""with open("diffseqs_100.pickle", "rb") as tp:
test_data = pickle.load(tp)"""
"""model: neural_network.MLPClassifier = joblib.load("MLP_full.joblib")
print("Predicting")
model.score(test_data[0], test_data[1])
predicted_vector = model.predict_proba(test_data[0])[:,1]
pr_cl = model.predict(test_data[0])
cm = confusion_matrix(test_data[1],pr_cl, labels=model.classes_)
MCC = (cm[0][0]*cm[1][1]-cm[0][1]*cm[1][0])\
/np.sqrt((cm[1][1]+cm[0][1])*(cm[1][1]+cm[1][0])*(cm[0][0]+cm[0][1])*(cm[0][0]+cm[1][0]))
ConfusionMatrixDisplay.from_predictions(test_data[1], pr_cl, colorbar=False, display_labels=model.classes_,
cmap="Blues", normalize="true", values_format=".4f")
plt.show()"""
"""for p, r, a in zip(pr_cl, test_data[1], test_data[2]):
if p == 1 and r == 0:
acc = a.split("|")[1]
ToxProtParse.retrieveAccessionFromUniprot(acc, "temp")"""
"""print(cm)
print(MCC)
pr_cl001=[lmap(pred,0.00001) for pred in predicted_vector]
cm001=confusion_matrix(test_data[1],pr_cl001, labels=model.classes_)
ConfusionMatrixDisplay.from_predictions(test_data[1],pr_cl001, colorbar=False, display_labels=model.classes_,
cmap="Blues", normalize="true", values_format=".4f")
plt.show()
MCC1 = (cm001[0][0]*cm001[1][1]-cm001[0][1]*cm001[1][0])\
/np.sqrt((cm001[1][1]+cm001[0][1])*(cm001[1][1]+cm001[1][0])*(cm001[0][0]+cm001[0][1])*(cm001[0][0]+cm001[1][0]))
print(cm001)
print(MCC1)
RocCurveDisplay.from_predictions(test_data[1],predicted_vector)
plt.plot([0,1], [0,1], linestyle="--", label="No skill")
plt.legend()
plt.show()
PrecisionRecallDisplay.from_predictions(test_data[1],predicted_vector)
noskill=collections.Counter(test_data[1])[1]/len(test_data[1])
plt.plot([0,1],[noskill,noskill],linestyle="--",label="No skill")
plt.legend()
plt.show()"""
###UnderSampling
"""
with open("pickled_embedded_train.pickle","rb") as tp:
training_data = pickle.load(tp)
XRes, YRes = NeighbourhoodCleaningRule(n_neighbors=5).fit_resample(training_data[0],training_data[1])
print(collections.Counter(YRes))
"""
###OverSampling
"""
with open("100_test_embedded.pickle","rb") as tp:
training_data = pickle.load(tp)
with open("100_train_embedded.pickle","rb") as tp:
test_data = pickle.load(tp)
alldata=[training_data[0]+test_data[0],training_data[1]+test_data[1]]
#alldata=[training_data[0],training_data[1]]
XRes, YRes = RandomOverSampler(shrinkage=0.25).fit_resample(alldata[0],alldata[1])
print(collections.Counter(YRes))
"""
###XGBoost
"""
with open("pickled_embedded_train.pickle", "rb") as tp:
training_data = pickle.load(tp)
model = ensemble.HistGradientBoostingClassifier(verbose=True, early_stopping=True, class_weight={0: 1, 1: 70},
max_iter=300)
model.fit(training_data[0], training_data[1])
with open("pickled_embedded_test.pickle", "rb") as tp:
test_data = pickle.load(tp)
model.score(test_data[0], test_data[1])
pr_cl = model.predict(test_data[0])
cm = confusion_matrix(test_data[1], pr_cl).ravel()
print(cm)"""
###Figs
###ToxPred3CM
"""#difftest = pd.read_csv("ToxinPred3_diffseqs_filt_predictions.csv")
postest = pd.read_csv("ToxinPred3_Toxin_predictions.csv")
negtest = pd.read_csv("ToxinPred3_Non-toxin_predictions.csv")
nlist = list(negtest["ML Score"])
plist = list(postest["ML Score"])
#difflist = list(difftest["ML Score"])
preds = [nlist + plist, np.concatenate((np.zeros(len(nlist)), np.ones(len(plist))))]
#dpreds = [difflist, np.ones(len(difflist))]
RocCurveDisplay.from_predictions(preds[1], preds[0])
plt.plot([0,1], [0,1], linestyle="--", label="No skill")
plt.legend()
plt.show()
#PrecisionRecallDisplay.from_predictions(preds[1],dpreds[0])
#noskill=collections.Counter(dpreds[1])[1]/len(dpreds[1])
#plt.plot([0,1],[noskill,noskill],linestyle="--",label="No skill")
#plt.legend()
#plt.show()
pr_cl=[lmap(pred, 0.5) for pred in preds[0]]
cm = confusion_matrix(preds[1],pr_cl)
print(cm)
ConfusionMatrixDisplay.from_predictions(preds[1],pr_cl, colorbar=False,
cmap="Blues", normalize="true", values_format=".4g")
plt.show()"""
"""preds = ["Не токсин"]*123575 + ["Токсин"]*56 + ["Не токсин"]*723 + ["Токсин"]*1313
reals = ["Не токсин"]*123631 + ["Токсин"]*2036
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Розмірність 100, голосування")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()
preds = ["Не токсин"]*123437 + ["Токсин"]*194 + ["Не токсин"]*342 + ["Токсин"]*1694
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Розмірність 100, найподібніший")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()
preds = ["Не токсин"]*123504 + ["Токсин"]*127 + ["Не токсин"]*513 + ["Токсин"]*1523
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Розмірність 200, голосування")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()
preds = ["Не токсин"]*123186 + ["Токсин"]*445 + ["Не токсин"]*215 + ["Токсин"]*1821
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Розмірність 200, найподібніший")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()
"""
preds = ["Не токсин"]*122940 + ["Токсин"]*691 + ["Не токсин"]*230 + ["Токсин"]*1806
reals = ["Не токсин"]*123631 + ["Токсин"]*2036
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Передбачення на основі BLASTp")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()
"""preds = ["Не токсин"]*123718 + ["Токсин"]*146 + ["Не токсин"]*426 + ["Токсин"]*1377
reals = ["Не токсин"]*123864 + ["Токсин"]*1803
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Порогове значення 0.5")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()
preds = ["Не токсин"]*121255 + ["Токсин"]*2609 + ["Не токсин"]*120 + ["Токсин"]*1683
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Порогове значення 0.00001")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()"""
"""preds = ["Не токсин"]*5607 + ["Токсин"]*61 + ["Не токсин"]*1998 + ["Токсин"]*4743
reals = ["Не токсин"]*5668 + ["Токсин"]*6741
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("ToxinPred3.0")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()"""
"""preds = ["Не токсин"]*718 + ["Токсин"]*386 + ["Не токсин"]*139 + ["Токсин"]*965
reals = ["Не токсин"]*1104 + ["Токсин"]*1104
ConfusionMatrixDisplay.from_predictions(reals,preds, colorbar=False,
cmap="Blues", normalize="true", values_format=".4f")
plt.title("Модель, порогове значення 0.00001")
plt.xlabel("Передбачений клас")
plt.ylabel("Реальний клас")
plt.show()"""