[2345e0]: / model / SALMON.py

Download this file

377 lines (322 with data), 17.5 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Zhi Huang
"""
import argparse, random
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torch.autograd import Variable
from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt
import math
import random
from imblearn.over_sampling import RandomOverSampler
import pandas as pd
from lifelines.statistics import logrank_test
from lifelines.utils import concordance_index
import tables
import csv
import numpy as np
import json
from tqdm import tqdm
import gc
import copy
class SALMON(nn.Module):
def __init__(self, input_dim, dropout_rate, length_of_data, label_dim):
super(SALMON, self).__init__()
self.length_of_data = length_of_data
hidden1 = 8
hidden2 = 4
if input_dim == length_of_data['mRNAseq']: # mRNAseq
self.encoder1 = nn.Sequential(nn.Linear(input_dim, hidden1),nn.Sigmoid())
self.classifier = nn.Sequential(nn.Linear(hidden1, label_dim),nn.Sigmoid())
if input_dim == length_of_data['miRNAseq']: # miRNAseq
self.encoder2 = nn.Sequential(nn.Linear(input_dim, hidden2),nn.Sigmoid())
self.classifier = nn.Sequential(nn.Linear(hidden2, label_dim),nn.Sigmoid())
if input_dim == length_of_data['mRNAseq'] + length_of_data['miRNAseq']: # mRNAseq + miRNAseq
self.encoder1 = nn.Sequential(nn.Linear(length_of_data['mRNAseq'], hidden1),nn.Sigmoid())
self.encoder2 = nn.Sequential(nn.Linear(length_of_data['miRNAseq'], hidden2),nn.Sigmoid())
self.classifier = nn.Sequential(nn.Linear(hidden1 + hidden2, label_dim),nn.Sigmoid())
if input_dim == length_of_data['mRNAseq'] + length_of_data['miRNAseq'] + length_of_data['CNB'] + length_of_data['TMB']: # mRNAseq + miRNAseq + CNB + TMB
hidden_cnv, hidden_tmb = length_of_data['CNB'], length_of_data['TMB']
self.encoder1 = nn.Sequential(nn.Linear(length_of_data['mRNAseq'], hidden1),nn.Sigmoid())
self.encoder2 = nn.Sequential(nn.Linear(length_of_data['miRNAseq'], hidden2),nn.Sigmoid())
self.classifier = nn.Sequential(nn.Linear(hidden1 + hidden2 + hidden_cnv + hidden_tmb, label_dim),nn.Sigmoid())
if input_dim == length_of_data['mRNAseq'] + length_of_data['miRNAseq'] + length_of_data['CNB'] + length_of_data['TMB'] + length_of_data['clinical']: # mRNAseq + miRNAseq + CNB + TMB + clinical
hidden_cnv, hidden_tmb, hidden_clinical = length_of_data['CNB'], length_of_data['TMB'], length_of_data['clinical']
self.encoder1 = nn.Sequential(nn.Linear(length_of_data['mRNAseq'], hidden1),nn.Sigmoid())
self.encoder2 = nn.Sequential(nn.Linear(length_of_data['miRNAseq'], hidden2),nn.Sigmoid())
self.classifier = nn.Sequential(nn.Linear(hidden1 + hidden2 + \
hidden_cnv + hidden_tmb + hidden_clinical, label_dim),nn.Sigmoid())
if input_dim == length_of_data['CNB'] + length_of_data['TMB'] + length_of_data['clinical']: # CNB + TMB + clinical
hidden_cnv, hidden_tmb, hidden_clinical = length_of_data['CNB'], length_of_data['TMB'], length_of_data['clinical']
self.classifier = nn.Sequential(nn.Linear(hidden_cnv + hidden_tmb + hidden_clinical, label_dim),nn.Sigmoid())
if input_dim == length_of_data['mRNAseq'] + length_of_data['miRNAseq'] + length_of_data['clinical']: # mRNAseq + miRNAseq + clinical
hidden_clinical = length_of_data['clinical']
self.encoder1 = nn.Sequential(nn.Linear(length_of_data['mRNAseq'], hidden1),nn.Sigmoid())
self.encoder2 = nn.Sequential(nn.Linear(length_of_data['miRNAseq'], hidden2),nn.Sigmoid())
self.classifier = nn.Sequential(nn.Linear(hidden1 + hidden2 + \
hidden_clinical, label_dim),nn.Sigmoid())
def forward(self, x):
input_dim = x.shape[1]
x_d = None
if input_dim == self.length_of_data['mRNAseq']: # mRNAseq
code1 = self.encoder1(x)
lbl_pred = self.classifier(code1) # predicted label
code = code1
if input_dim == self.length_of_data['miRNAseq']: # miRNAseq
code2 = self.encoder2(x)
lbl_pred = self.classifier(code2) # predicted label
code = code2
if input_dim == self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq']: # mRNAseq + miRNAseq
code1 = self.encoder1(x[:,0:self.length_of_data['mRNAseq']])
code2 = self.encoder2(x[:,self.length_of_data['mRNAseq']:])
lbl_pred = self.classifier(torch.cat((code1, code2), 1)) # predicted label
code = torch.cat((code1, code2), 1)
if input_dim == self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq'] + self.length_of_data['CNB'] + self.length_of_data['TMB']: # mRNAseq + miRNAseq + CNB + TMB
code1 = self.encoder1(x[:,0:self.length_of_data['mRNAseq']])
code2 = self.encoder2(x[:,self.length_of_data['mRNAseq']: (self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq'])])
lbl_pred = self.classifier(torch.cat((code1, code2, x[:,(self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq']):]), 1)) # predicted label
code = torch.cat((code1, code2), 1)
if input_dim == self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq'] + self.length_of_data['CNB'] + self.length_of_data['TMB'] + self.length_of_data['clinical']: # mRNAseq + miRNAseq + CNB + TMB + clinical
code1 = self.encoder1(x[:,0:self.length_of_data['mRNAseq']])
code2 = self.encoder2(x[:,self.length_of_data['mRNAseq']: (self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq'])])
lbl_pred = self.classifier(torch.cat((code1, code2, x[:, (self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq']):]), 1)) # predicted label
code = torch.cat((code1, code2), 1)
if input_dim == self.length_of_data['CNB'] + self.length_of_data['TMB'] + self.length_of_data['clinical']: # CNB + TMB + clinical
lbl_pred = self.classifier(x) # predicted label
code = torch.FloatTensor([0])
if input_dim == self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq'] + self.length_of_data['clinical']: # mRNAseq + miRNAseq + clinical
code1 = self.encoder1(x[:,0:self.length_of_data['mRNAseq']])
code2 = self.encoder2(x[:,self.length_of_data['mRNAseq']: (self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq'])])
lbl_pred = self.classifier(torch.cat((code1, code2, x[:, (self.length_of_data['mRNAseq'] + self.length_of_data['miRNAseq']):]), 1)) # predicted label
code = torch.cat((code1, code2), 1)
return x_d, code, lbl_pred
def accuracy(output, labels):
preds = output.max(1)[1].type_as(labels)
correct = preds.eq(labels).double()
correct = correct.sum()
return correct / len(labels)
def accuracy_cox(hazards, labels):
# This accuracy is based on estimated survival events against true survival events
hazardsdata = hazards.cpu().numpy().reshape(-1)
median = np.median(hazardsdata)
hazards_dichotomize = np.zeros([len(hazardsdata)], dtype=int)
hazards_dichotomize[hazardsdata > median] = 1
labels = labels.data.cpu().numpy()
correct = np.sum(hazards_dichotomize == labels)
return correct / len(labels)
def cox_log_rank(hazards, labels, survtime_all):
hazardsdata = hazards.cpu().numpy().reshape(-1)
median = np.median(hazardsdata)
hazards_dichotomize = np.zeros([len(hazardsdata)], dtype=int)
hazards_dichotomize[hazardsdata > median] = 1
survtime_all = survtime_all.data.cpu().numpy().reshape(-1)
idx = hazards_dichotomize == 0
labels = labels.data.cpu().numpy()
T1 = survtime_all[idx]
T2 = survtime_all[~idx]
E1 = labels[idx]
E2 = labels[~idx]
results = logrank_test(T1, T2, event_observed_A=E1, event_observed_B=E2)
pvalue_pred = results.p_value
return(pvalue_pred)
def CIndex(hazards, labels, survtime_all):
labels = labels.data.cpu().numpy()
concord = 0.
total = 0.
N_test = labels.shape[0]
labels = np.asarray(labels, dtype=bool)
for i in range(N_test):
if labels[i] == 1:
for j in range(N_test):
if survtime_all[j] > survtime_all[i]:
total = total + 1
if hazards[j] < hazards[i]: concord = concord + 1
elif hazards[j] < hazards[i]: concord = concord + 0.5
return(concord/total)
def CIndex_lifeline(hazards, labels, survtime_all):
labels = labels.data.cpu().numpy()
hazards = hazards.cpu().numpy().reshape(-1)
return(concordance_index(survtime_all, -hazards, labels))
def frobenius_norm_loss(a, b):
loss = torch.sqrt(torch.sum(torch.abs(a-b)**2))
return loss
def test(model, datasets, whichset, length_of_data, batch_size, cuda, verbose):
x = datasets[whichset]['x']
e = datasets[whichset]['e']
t = datasets[whichset]['t']
X = torch.FloatTensor(x)
OS_event = torch.LongTensor(e)
OS = torch.FloatTensor(t)
dataloader = DataLoader(X, batch_size=batch_size, num_workers=1, pin_memory=True, shuffle=False)
lblloader = DataLoader(OS_event, batch_size=batch_size, num_workers=1, pin_memory=True, shuffle=False)
OSloader = DataLoader(OS, batch_size=batch_size, num_workers=1, pin_memory=True, shuffle=False)
lbl_pred_all = None
lbl_all = None
survtime_all = None
code_final = None
loss_nn_sum = 0
model.eval()
iter = 0
for data, lbl, survtime in zip(dataloader, lblloader, OSloader):
graph = data
graph = Variable(graph)
lbl = Variable(lbl)
if cuda:
model = model.cuda()
graph = graph.cuda()
lbl = lbl.cuda()
# ===================forward=====================
output, code, lbl_pred = model(graph)
if iter == 0:
lbl_pred_all = lbl_pred
lbl_all = lbl
survtime_all = survtime
code_final = code
else:
lbl_pred_all = torch.cat([lbl_pred_all, lbl_pred])
lbl_all = torch.cat([lbl_all, lbl])
survtime_all = torch.cat([survtime_all, survtime])
code_final = torch.cat([code_final, code])
current_batch_len = len(survtime)
R_matrix_test = np.zeros([current_batch_len, current_batch_len], dtype=int)
for i in range(current_batch_len):
for j in range(current_batch_len):
R_matrix_test[i,j] = survtime[j] >= survtime[i]
test_R = torch.FloatTensor(R_matrix_test)
test_R = Variable(test_R)
if cuda:
test_R = test_R.cuda()
test_ystatus = lbl
theta = lbl_pred.reshape(-1)
exp_theta = torch.exp(theta)
loss_nn = -torch.mean( (theta - torch.log(torch.sum( exp_theta*test_R ,dim=1))) * test_ystatus.float() )
loss_nn_sum = loss_nn_sum + loss_nn.data.item()
iter += 1
code_final_4_original_data = code_final.data.cpu().numpy()
acc_test = accuracy_cox(lbl_pred_all.data, lbl_all)
pvalue_pred = cox_log_rank(lbl_pred_all.data, lbl_all, survtime_all)
c_index = CIndex_lifeline(lbl_pred_all.data, lbl_all, survtime_all)
if verbose > 0:
print('\n[{:s}]\t\tloss (nn):{:.4f}'.format(whichset, loss_nn_sum),
'c_index: {:.4f}, p-value: {:.3e}'.format(c_index, pvalue_pred))
return(code_final_4_original_data, loss_nn_sum, acc_test, \
pvalue_pred, c_index, lbl_pred_all.data.cpu().numpy().reshape(-1), OS_event, survtime_all)
def init_weights(m):
if type(m) == nn.Linear:
m.weight.data.normal_(0, 0.5)
def train(datasets, num_epochs, batch_size, learning_rate, dropout_rate,
lambda_1, length_of_data, cuda, measure, verbose):
x = datasets['train']['x']
e = datasets['train']['e']
t = datasets['train']['t']
nodes_in = x.shape[1]
X = torch.FloatTensor(x)
OS_event = torch.LongTensor(e)
OS = torch.FloatTensor(t)
dataloader = DataLoader(X, batch_size=batch_size, num_workers=0, pin_memory=True, shuffle=False)
lblloader = DataLoader(OS_event, batch_size=batch_size, num_workers=0, pin_memory=True, shuffle=False)
OSloader = DataLoader(OS, batch_size=batch_size, num_workers=0, pin_memory=True, shuffle=False)
cudnn.deterministic = True
torch.cuda.manual_seed_all(666)
torch.manual_seed(666)
random.seed(666)
model = SALMON(nodes_in, dropout_rate, length_of_data, label_dim = 1)
if cuda:
model.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=0)
c_index_list = {}
c_index_list['train'] = []
c_index_list['test'] = []
loss_nn_all = []
pvalue_all = []
c_index_all = []
acc_train_all = []
c_index_best = 0
code_output = None
for epoch in tqdm(range(num_epochs)):
model.train()
lbl_pred_all = None
lbl_all = None
survtime_all = None
code_final = None
loss_nn_sum = 0
iter = 0
gc.collect()
for data, lbl, survtime in zip(dataloader, lblloader, OSloader):
optimizer.zero_grad() # zero the gradient buffer
graph = data
if cuda:
model = model.cuda()
graph = graph.cuda()
lbl = lbl.cuda()
# ===================forward=====================
output, code, lbl_pred = model(graph)
if iter == 0:
lbl_pred_all = lbl_pred
survtime_all = survtime
lbl_all = lbl
code_final = code
else:
lbl_pred_all = torch.cat([lbl_pred_all, lbl_pred])
lbl_all = torch.cat([lbl_all, lbl])
survtime_all = torch.cat([survtime_all, survtime])
code_final = torch.cat([code_final, code])
# This calculation credit to Travers Ching https://github.com/traversc/cox-nnet
# Cox-nnet: An artificial neural network method for prognosis prediction of high-throughput omics data
current_batch_len = len(survtime)
R_matrix_train = np.zeros([current_batch_len, current_batch_len], dtype=int)
for i in range(current_batch_len):
for j in range(current_batch_len):
R_matrix_train[i,j] = survtime[j] >= survtime[i]
train_R = torch.FloatTensor(R_matrix_train)
if cuda:
train_R = train_R.cuda()
train_ystatus = lbl
theta = lbl_pred.reshape(-1)
exp_theta = torch.exp(theta)
loss_nn = -torch.mean( (theta - torch.log(torch.sum( exp_theta*train_R ,dim=1))) * train_ystatus.float() )
l1_reg = None
for W in model.parameters():
if l1_reg is None:
l1_reg = torch.abs(W).sum()
else:
l1_reg = l1_reg + torch.abs(W).sum() # torch.abs(W).sum() is equivalent to W.norm(1)
loss = loss_nn + lambda_1 * l1_reg
if verbose > 0:
print("\nloss_nn: %.4f, L1: %.4f" % (loss_nn, lambda_1 * l1_reg))
loss_nn_sum = loss_nn_sum + loss_nn.data.item()
# ===================backward====================
loss.backward()
optimizer.step()
iter += 1
torch.cuda.empty_cache()
code_final_4_original_data = code_final.data.cpu().numpy()
if measure or epoch == (num_epochs - 1):
acc_train = accuracy_cox(lbl_pred_all.data, lbl_all)
pvalue_pred = cox_log_rank(lbl_pred_all.data, lbl_all, survtime_all)
c_index = CIndex_lifeline(lbl_pred_all.data, lbl_all, survtime_all)
c_index_list['train'].append(c_index)
if c_index > c_index_best:
c_index_best = c_index
code_output = code_final_4_original_data
if verbose > 0:
print('\n[Training]\t loss (nn):{:.4f}'.format(loss_nn_sum),
'c_index: {:.4f}, p-value: {:.3e}'.format(c_index, pvalue_pred))
pvalue_all.append(pvalue_pred)
c_index_all.append(c_index)
loss_nn_all.append(loss_nn_sum)
acc_train_all.append(acc_train)
whichset = 'test'
code_validation, loss_nn_sum, acc_test, pvalue_pred, c_index_pred, lbl_pred_all, OS_event, OS = \
test(model, datasets, whichset, length_of_data, batch_size, cuda, verbose)
c_index_list['test'].append(c_index_pred)
return(model, loss_nn_all, pvalue_all, c_index_all, c_index_list, acc_train_all, code_output)