-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
413 lines (382 loc) · 19.3 KB
/
main.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
'''
GitHub - kenshohara/3D-ResNets-PyTorch: 3D ResNets for Action Recognition (CVPR 2018)
'''
from __future__ import print_function
import os
import sys
import json
import h5py
import numpy as np
import deepdish as dd
from scipy.io import loadmat
import torch
from torch import nn
from torch import optim
from torch.optim import lr_scheduler
from opts import parse_opts
from model.net import resnet10
from model.data_loader_crnn import fMRIDataset_CRNN,get_loader
from model.data_loader_2c import fMRIDataset_2C
from model.data_loader import fMRIDataset
from utils import Logger,get_test_data,perf_measure
from train import train_epoch
from validation import val_epoch
import test
import pandas as pd
from model.C3D import MyNet
from model.CNN_LSTM import CNN_LSTM
from torch.autograd import Variable
import os
import copy
import pdb
os.environ['CUDA_VISIBLE_DEVICES']='0'
torch.manual_seed(666)
def main():
opt = parse_opts()
print(opt)
#pdb.set_trace()
if not os.path.exists(opt.result_path):
os.mkdir(opt.result_path)
with open(os.path.join(opt.result_path, 'opts.json'), 'w') as opt_file:
json.dump(vars(opt), opt_file)
device = torch.device("cuda" if opt.use_cuda else "cpu")
# Read Phenotype
csv = pd.read_csv(opt.csv_dir)
if opt.cross_val:
for fold in range(5): # change back to 5
train_ID = dd.io.load(os.path.join(opt.MAT_dir, opt.splits))[fold]['X_train']
val_ID = dd.io.load(os.path.join(opt.MAT_dir, opt.splits))[fold]['X_test']
# ==========================================================================#
# 1. Network Initialization #
# ==========================================================================#
torch.manual_seed(opt.manual_seed)
if opt.architecture == 'ResNet':
kwargs = {'inchn': opt.win_size, 'sample_size': opt.sample_size, 'sample_duration': opt.sample_duration,
'num_classes': opt.n_classes}
model = resnet10(**kwargs).to(device)
elif opt.architecture == 'NC3D':
model = MyNet(opt.win_size, opt.nb_filter, opt.batch_size).to(device)
elif opt.architecture == 'CRNN':
model = CNN_LSTM(opt.win_size, opt.nb_filter, opt.batch_size, opt.sample_size, opt.sample_duration, opt.rep).to(device)
else:
print('Architecture is not available.')
raise LookupError
print(model)
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
num_params = sum([np.prod(p.size()) for p in model_parameters])
print('number of trainable parameters:', num_params)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class_weights = torch.FloatTensor(opt.weights).to(device)
criterion = nn.CrossEntropyLoss(weight= class_weights)
criterion.to(device)
# ==========================================================================#
# 2. Setup Dataloading Paramters #
# ==========================================================================#
'''load subjects ID'''
ID = csv['SUB_ID'].values
win_size = opt.win_size # num of channel input
T = opt.sample_duration # total length of fMRI
num_rep = T // win_size # num of repeat the ID
# ==========================================================================#
# 3. Training and Validation #
# ==========================================================================#
if opt.architecture == 'ResNet':
training_data = fMRIDataset(opt.datadir, win_size, train_ID, T, csv)
elif opt.architecture == 'NC3D':
training_data = fMRIDataset_2C(opt.datadir, train_ID)
elif opt.architecture == 'CRNN':
training_data = fMRIDataset_CRNN(opt.datadir, win_size, train_ID, T, csv)
else:
print('Architecture is not available.')
raise LookupError
train_loader = torch.utils.data.DataLoader(
training_data,
batch_size=opt.batch_size,
shuffle=True,
num_workers=opt.n_threads,
pin_memory=False)
log_path = os.path.join(opt.result_path, str(fold))
if not os.path.exists(log_path):
os.mkdir(log_path)
train_logger = Logger(
os.path.join(log_path, 'train.log'),
['epoch', 'loss', 'acc', 'lr'])
train_batch_logger = Logger(
os.path.join(log_path, 'train_batch.log'),
['epoch', 'batch', 'iter', 'loss', 'acc', 'lr'])
'''optimization'''
if opt.nesterov:
dampening = 0
else:
dampening = opt.dampening
if opt.optimizer == 'sgd':
optimizer = optim.SGD(
model.parameters(),
lr=opt.learning_rate,
momentum=opt.momentum,
dampening=dampening,
weight_decay=opt.weight_decay,
nesterov=opt.nesterov)
elif opt.optimizer == 'adam':
optimizer = optim.Adam(
model.parameters(),
lr=opt.learning_rate,
weight_decay=opt.weight_decay
)
elif opt.optimizer == 'adadelta':
optimizer = optim.Adadelta(
model.parameters(),
lr=opt.learning_rate,
weight_decay=opt.weight_decay
)
scheduler = lr_scheduler.ReduceLROnPlateau(
optimizer, 'min', patience=opt.lr_patience)
scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2)
if not opt.no_val:
if opt.architecture == 'ResNet':
validation_data = fMRIDataset(opt.datadir, win_size, val_ID, T, csv)
elif opt.architecture == 'NC3D':
validation_data = fMRIDataset_2C(opt.datadir, val_ID)
elif opt.architecture == 'CRNN':
validation_data = fMRIDataset_CRNN(opt.datadir, win_size, val_ID, T, csv)
val_loader = torch.utils.data.DataLoader(
validation_data,
batch_size=opt.n_val_samples,
shuffle=False,
num_workers=opt.n_threads,
pin_memory=False)
val_logger = Logger(
os.path.join(log_path, 'val.log'), ['epoch', 'loss', 'acc'])
if opt.resume_path:
print('loading checkpoint {}'.format(opt.resume_path))
checkpoint = torch.load(opt.resume_path)
# assert opt.arch == checkpoint['arch']
opt.begin_epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['state_dict'])
if not opt.no_train:
optimizer.load_state_dict(checkpoint['optimizer'])
print('run')
best_loss = 1e4
for i in range(opt.begin_epoch, opt.n_epochs + 1):
if not opt.no_train:
train_epoch(i, train_loader, model, criterion, optimizer, opt, log_path,
train_logger, train_batch_logger)
if not opt.no_val:
validation_loss = val_epoch(i, val_loader, model, criterion, opt,
val_logger)
if validation_loss < best_loss:
best_loss = validation_loss
best_model_wts = copy.deepcopy(model.state_dict())
torch.save(best_model_wts, os.path.join(log_path, str(fold) + '_best.pth'))
if not opt.no_train and not opt.no_val:
#scheduler.step(validation_loss)
scheduler.step()
model_wts = copy.deepcopy(model.state_dict())
torch.save(model_wts, os.path.join(log_path, str(fold) +'_epoch_' +str(i)+ '.pth'))
# =========================================================================#
# 4. Testing #
# =========================================================================#
if opt.test:
model = MyNet(opt.win_size, opt.nb_filter, opt.batch_size).to(device)
model.load_state_dict(torch.load(os.path.join(log_path, str(fold) + '_best.pth')))
test_details_logger = Logger(os.path.join(log_path, 'test_details.log'),['sub_id','pos','neg'])
test_logger = Logger(os.path.join(log_path, 'test.log'), ['fold', 'real_Y', 'pred_Y', 'acc', 'sen','spec','ppv','npv'])
real_Y = []
pred_Y = []
model.eval()
if opt.no_val:
if opt.architecture == 'ResNet':
validation_data = fMRIDataset(opt.datadir, win_size, val_ID, T, csv)
elif opt.architecture == 'NC3D':
validation_data = fMRIDataset_2C(opt.datadir, val_ID)
elif opt.architecture == 'CRNN':
validation_data = fMRIDataset_CRNN(opt.datadir, win_size, val_ID, T, csv)
test_loader = torch.utils.data.DataLoader(
validation_data,
batch_size=146+1-opt.s_sz,
shuffle=False,
num_workers=opt.n_threads,
pin_memory=False)
with torch.no_grad():
for i, (inputs, targets) in enumerate(test_loader):
real_Y.append(targets[0])
inputs, targets = inputs.to(device), targets.to(device)
inputs = Variable(inputs).float()
targets = Variable(targets).long()
outputs = model(inputs)
rest = np.argmax(outputs.detach().cpu().numpy(), axis=1)
pos = np.sum(rest == targets.detach().cpu().numpy())
neg = len(rest) - pos
print('pos:', pos, ' and neg:', neg)
test_details_logger.log({'sub_id': val_ID[i*142], 'pos': pos, 'neg': neg})
if np.sum(rest==1) >= np.sum(rest==0):
pred_Y.append(1)
else:
pred_Y.append(0)
TP, FP, TN, FN = perf_measure(real_Y, pred_Y )
acc = (TP+TN)/(TP+TN+FP+FN)
sen = TP/(TP+FN)
spec = TN/(TN+FP)
ppv = TP/(TP+FP)
npv = TN/(TN+FN)
test_logger.log({'fold':fold,'real_Y':real_Y,'pred_Y':pred_Y,'acc':acc,'sen':sen,'spec':spec,'ppv':ppv,'npv':npv})
else:
fold = opt.fold
train_ID = dd.io.load(os.path.join(opt.MAT_dir, opt.splits))[fold]['X_train']
val_ID = dd.io.load(os.path.join(opt.MAT_dir, opt.splits))[fold]['X_test']
# ==========================================================================#
# 1. Network Initialization #
# ==========================================================================#
torch.manual_seed(opt.manual_seed)
if opt.architecture == 'ResNet':
kwargs = {'inchn': opt.win_size, 'sample_size': opt.sample_size, 'sample_duration': opt.sample_duration,
'num_classes': opt.n_classes}
model = resnet10(**kwargs).to(device)
elif opt.architecture == 'NC3D':
model = MyNet(opt.win_size, opt.nb_filter, opt.batch_size).to(device)
elif opt.architecture == 'CRNN':
model = CNN_LSTM(opt.win_size, opt.nb_filter, opt.batch_size, opt.s_sz, opt.sample_duration, opt.rep).to(device)
else:
print('Architecture is not available.')
raise LookupError
print(model)
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
num_params = sum([np.prod(p.size()) for p in model_parameters])
print('number of trainable parameters:', num_params)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class_weights = torch.FloatTensor(opt.weights).to(device)
criterion = nn.CrossEntropyLoss(weight=class_weights)
criterion.to(device)
# ==========================================================================#
# 2. Setup Dataloading Paramters #
# ==========================================================================#
'''load subjects ID'''
win_size = opt.win_size # num of channel input
T = opt.sample_duration # total length of fMRI
# ==========================================================================#
# 3. Training and Validation #
# ==========================================================================#
# repeat the ID, in order to visit all the volumes in fMRI, this will be input to the dataloader
if opt.architecture == 'ResNet':
training_data = fMRIDataset(opt.datadir, opt.s_sz, train_ID, T, csv, opt.rep)
elif opt.architecture == 'NC3D':
training_data = fMRIDataset_2C(opt.datadir,train_ID)
elif opt.architecture == 'CRNN':
training_data = fMRIDataset_CRNN(opt.datadir, opt.s_sz, train_ID, T, csv, opt.rep)
train_loader = torch.utils.data.DataLoader(
training_data,
batch_size=opt.batch_size,
shuffle=True,
#num_workers=opt.n_threads,
pin_memory=True)
log_path = opt.result_path
print('log_path',log_path)
if not os.path.exists(log_path):
os.mkdir(log_path)
train_logger = Logger(
os.path.join(log_path, 'train.log'),
['epoch', 'loss', 'acc', 'lr'])
train_batch_logger = Logger(
os.path.join(log_path, 'train_batch.log'),
['epoch', 'batch', 'iter', 'loss', 'acc', 'lr'])
'''optimization'''
if opt.nesterov:
dampening = 0
else:
dampening = opt.dampening
if opt.optimizer =='sgd':
optimizer = optim.SGD(
model.parameters(),
lr=opt.learning_rate,
momentum=opt.momentum,
dampening=dampening,
weight_decay=opt.weight_decay,
nesterov=opt.nesterov)
elif opt.optimizer =='adam':
optimizer = optim.Adam(
model.parameters(),
lr=opt.learning_rate,
weight_decay=opt.weight_decay
)
elif opt.optimizer =='adadelta':
optimizer = optim.Adadelta(
model.parameters(),
lr=opt.learning_rate,
weight_decay=opt.weight_decay
)
# scheduler = lr_scheduler.ReduceLROnPlateau(
# optimizer, 'min', patience=opt.lr_patience)
scheduler = lr_scheduler.StepLR(optimizer, step_size=4, gamma=0.1)
if not opt.no_val:
if opt.architecture == 'ResNet':
validation_data = fMRIDataset(opt.datadir, opt.s_sz, val_ID, T, csv, opt.rep)
elif opt.architecture == 'NC3D':
validation_data = fMRIDataset_2C(opt.datadir, val_ID)
elif opt.architecture == 'CRNN':
validation_data = fMRIDataset_CRNN(opt.datadir, opt.s_sz, val_ID, T, csv, opt.rep)
val_loader = torch.utils.data.DataLoader(
validation_data,
batch_size=opt.n_val_samples,
shuffle=False,
#num_workers=opt.n_threads,
pin_memory=True)
val_logger = Logger(
os.path.join(log_path, 'val.log'), ['epoch', 'loss', 'acc'])
if opt.resume_path:
print('loading checkpoint {}'.format(opt.resume_path))
checkpoint = torch.load(opt.resume_path)
# assert opt.arch == checkpoint['arch']
opt.begin_epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['state_dict'])
if not opt.no_train:
optimizer.load_state_dict(checkpoint['optimizer'])
print('run')
for i in range(opt.begin_epoch, opt.n_epochs + 1):
if not opt.no_train:
train_epoch(i, train_loader, model, criterion, optimizer, opt, log_path,
train_logger, train_batch_logger)
if not opt.no_val: # when epoch is greater then 5, we start to do validation
validation_loss = val_epoch(i, val_loader, model, criterion, opt,
val_logger)
if not opt.no_train and not opt.no_val:
scheduler.step(validation_loss)
# =========================================================================#
# 4. Testing #
# =========================================================================#
if opt.test:
test_details_logger = Logger(os.path.join(opt.result_path, 'test_details.log'), ['sub_id', 'pos', 'neg'])
test_logger = Logger(os.path.join(opt.result_path, 'test.log'),
['fold', 'real_Y', 'pred_Y', 'acc', 'sen', 'spec', 'ppv', 'npv'])
real_Y = []
pred_Y = []
model.eval()
test_loader = torch.utils.data.DataLoader(
validation_data,
batch_size=142,
shuffle=False,
num_workers=opt.n_threads,
pin_memory=False)
with torch.no_grad():
for i, (inputs, targets) in enumerate(test_loader):
real_Y.append(targets)
inputs, targets = inputs.to(device), targets.to(device)
inputs = Variable(inputs).float()
targets = Variable(targets).long()
outputs = model(inputs)
rest = np.argmax(outputs.detach().cpu().numpy(), axis=1)
pred_Y.append(outputs.detach().cpu().numpu())
pos = np.sum(rest == targets.detach().cpu().numpu())
neg = len(rest) - pos
#print('pos:', pos, ' and neg:', neg)
test_details_logger.log({'sub_id': val_ID[i * 142], 'pos': pos, 'neg': neg})
TP, FP, TN, FN = perf_measure(real_Y, pred_Y)
acc = (TP + TN) / (TP + TN + FP + FN)
sen = TP / (TP + FN)
spec = TN / (TN + FP)
ppv = TP / (TP + FP)
npv = TN / (TN + FN)
test_logger.log(
{'fold': fold, 'real_Y': real_Y, 'pred_Y': pred_Y, 'acc': acc, 'sen': sen, 'spec': spec, 'ppv': ppv,
'npv': npv})
if __name__ == '__main__':
main()