-
Notifications
You must be signed in to change notification settings - Fork 2
/
main_chir.py
269 lines (223 loc) · 9.08 KB
/
main_chir.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
'''
Date: 2022-11-23 11:29:36
LastEditors: yuhhong
LastEditTime: 2022-12-12 12:57:28
'''
import os
import argparse
import numpy as np
from tqdm import tqdm
import yaml
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader, SubsetRandomSampler, ConcatDataset
from torch.utils.tensorboard import SummaryWriter
from torch.optim.lr_scheduler import MultiStepLR
import random
from rdkit import Chem
# suppress rdkit warning
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
from sklearn.metrics import roc_auc_score, accuracy_score
from dataset import ChiralityDataset
from model import MolNet_CSP
from utils import set_seed, CE_loss
def train(model, device, loader, optimizer, batch_size, num_points):
y_true = []
y_pred = []
for step, batch in enumerate(tqdm(loader, desc="Iteration")):
_, _, _, x, y = batch
x = x.to(device).to(torch.float32)
x = x.permute(0, 2, 1)
y = y.to(device)
idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points
model.train()
pred = model(x, idx_base)
# print('pred', pred.size())
loss = CE_loss(pred, y)
loss.backward()
optimizer.step()
optimizer.zero_grad()
y_true.append(y.detach().cpu())
y_pred.append(pred.detach().cpu())
y_true = torch.cat(y_true, dim=0)
y_pred = torch.cat(y_pred, dim=0)
return y_true, y_pred
def eval(model, device, loader, batch_size, num_points):
model.eval()
y_true = []
y_pred = []
smiles_list = []
id_list = []
mbs = []
for _, batch in enumerate(tqdm(loader, desc="Iteration")):
mol_id, smiles_iso, mb, x, y = batch
x = x.to(device).to(torch.float32)
x = x.permute(0, 2, 1)
y = y.to(device)
idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points
with torch.no_grad():
pred = model(x, idx_base)
y_true.append(y.detach().cpu())
y_pred.append(pred.detach().cpu())
smiles_list.extend(smiles_iso)
id_list.extend(mol_id)
mbs.extend(mb.tolist())
y_true = torch.cat(y_true, dim=0)
y_pred = torch.cat(y_pred, dim=0)
return id_list, smiles_list, mbs, y_true, y_pred
def batch_filter(supp):
for mol in supp: # remove empty molecule
if mol is None:
continue
if len(Chem.MolToMolBlock(mol).split("\n")) <= 6:
continue
yield mol
if __name__ == "__main__":
# Training settings
parser = argparse.ArgumentParser(description='3DMolCSP (train)')
parser.add_argument('--config', type=str, default = './configs/molnet_train_s.yaml',
help='Path to configuration')
parser.add_argument('--csp_no', type=int, default=0,
help='charility phase number [0, 19]')
parser.add_argument('--log_dir', type=str, default="./logs/",
help='tensorboard log directory')
parser.add_argument('--checkpoint', type=str, default = '',
help='path to save checkpoint')
parser.add_argument('--resume_path', type=str, default='',
help='Pretrained model path')
parser.add_argument('--transfer', action='store_true',
help='Whether to load the pretrained encoder')
parser.add_argument('--device', type=int, default=0,
help='which gpu to use if any (default: 0)')
parser.add_argument('--no_cuda', type=bool, default=False,
help='enables CUDA training')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
set_seed(42)
# load the configuration file
with open(args.config, 'r') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
device = torch.device("cuda:" + str(args.device)) if torch.cuda.is_available() else torch.device("cpu")
model = MolNet_CSP(config['model_para'], args.device).to(device)
num_params = sum(p.numel() for p in model.parameters())
# print(f'{str(model)} #Params: {num_params}')
print('#Params: {}'.format(num_params))
print("Loading the data...")
supp = Chem.SDMolSupplier(config['paths']['train_data'])
train_set = ChiralityDataset([item for item in batch_filter(supp)],
num_points=config['model_para']['num_atoms'],
csp_no=args.csp_no,
flipping=False)
supp_ena = Chem.SDMolSupplier(config['paths']['train_data'])
train_set_ena = ChiralityDataset([item for item in batch_filter(supp_ena)],
num_points=config['model_para']['num_atoms'],
csp_no=args.csp_no,
flipping=True)
train_indices = train_set.balance_indices(list(range(len(train_set)))) # use this line to make balance sampling
train_indices += [i+len(train_set) for i in train_indices] # add enantiomers (use the same indexes for two configurations prohibit data leaking)
train_sampler = SubsetRandomSampler(train_indices)
train_set = ConcatDataset([train_set, train_set_ena]) # concat two configurations' datasets
train_loader = DataLoader(train_set,
batch_size=config['train_para']['batch_size'],
num_workers=config['train_para']['num_workers'],
drop_last=True,
sampler=train_sampler)
supp = Chem.SDMolSupplier(config['paths']['valid_data'])
valid_set = ChiralityDataset([item for item in batch_filter(supp)],
num_points=config['model_para']['num_atoms'],
csp_no=args.csp_no,
flipping=False)
supp_ena = Chem.SDMolSupplier(config['paths']['valid_data'])
valid_set_ena = ChiralityDataset([item for item in batch_filter(supp_ena)],
num_points=config['model_para']['num_atoms'],
csp_no=args.csp_no,
flipping=True)
valid_set = ConcatDataset([valid_set, valid_set_ena]) # concat two configurations' datasets
valid_loader = DataLoader(valid_set,
batch_size=config['train_para']['batch_size'],
num_workers=config['train_para']['num_workers'],
drop_last=True)
print('Load {} test data from {}.'.format(len(valid_set), config['paths']['valid_data']))
optimizer = optim.Adam(model.parameters(),
lr=config['train_para']['lr'],
weight_decay=config['train_para']['weight_decay'])
scheduler = MultiStepLR(optimizer,
milestones=config['train_para']['scheduler']['milestones'],
gamma=config['train_para']['scheduler']['gamma'])
best_valid_auc = 0
best_valid_acc = 0
if args.resume_path != '':
if args.transfer:
print("Load the pretrained encoder...")
state_dict = torch.load(args.resume_path, map_location=device)['model_state_dict']
encoder_dict = {}
for name, param in state_dict.items():
if name.startswith("encoder"):
encoder_dict[name] = param
model.load_state_dict(encoder_dict, strict=False)
else:
print("Load the checkpoints...")
model.load_state_dict(torch.load(args.resume_path, map_location=device)['model_state_dict'])
optimizer.load_state_dict(torch.load(args.resume_path, map_location=device)['optimizer_state_dict'])
scheduler.load_state_dict(torch.load(args.resume_path, map_location=device)['scheduler_state_dict'])
best_valid_auc = torch.load(args.resume_path, map_location=device)['best_val_auc']
model.to(device)
if args.checkpoint != '':
checkpoint_dir = "/".join(args.checkpoint.split('/')[:-1])
os.makedirs(checkpoint_dir, exist_ok = True)
if args.log_dir != '':
writer = SummaryWriter(log_dir=args.log_dir)
early_stop_step = 5
early_stop_patience = 0
for epoch in range(1, config['train_para']['epochs'] + 1):
print("\n=====Epoch {}".format(epoch))
print('Training...')
y_true, y_pred = train(model, device, train_loader, optimizer,
config['train_para']['batch_size'],
config['model_para']['num_atoms'])
train_auc = roc_auc_score(np.array(y_true), y_pred, multi_class='ovr',)
y_pred = torch.argmax(y_pred, dim=1)
train_acc = accuracy_score(y_true, y_pred)
print('Evaluating...')
id_list, smiles_list, mbs, y_true, y_pred = eval(model, device, valid_loader,
config['train_para']['batch_size'],
config['model_para']['num_atoms'])
try:
valid_auc = roc_auc_score(np.array(y_true), y_pred, multi_class='ovr',)
except:
valid_auc = np.nan
y_pred = torch.argmax(y_pred, dim=1)
valid_acc = accuracy_score(y_true, y_pred)
print("Train ACC: {} Train AUC: {}\nValid ACC: {} Valid AUC: {}\n".format(train_acc, train_auc, valid_acc, valid_auc))
if args.log_dir != '':
writer.add_scalar('valid/auc', valid_auc, epoch)
writer.add_scalar('train/auc', train_auc, epoch)
if (not np.isnan(valid_auc) and valid_auc > best_valid_auc) or \
(np.isnan(valid_auc) and valid_acc >= best_valid_acc):
best_valid_acc = valid_acc
best_valid_auc = valid_auc
if args.checkpoint != '':
print('Saving checkpoint...')
checkpoint = {'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict(),
'best_val_auc': best_valid_auc,
'num_params': num_params}
torch.save(checkpoint, args.checkpoint)
early_stop_patience = 0
print('Early stop patience reset')
else:
early_stop_patience += 1
print('Early stop count: {}/{}'.format(early_stop_patience, early_stop_step))
scheduler.step()
print('Best ACC so far: {}'.format(best_valid_acc))
print('Best AUC so far: {}'.format(best_valid_auc))
if early_stop_patience == early_stop_step:
print('Early stop!')
break
if args.log_dir != '':
writer.close()