-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
198 lines (148 loc) · 6.23 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
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torch.utils.data import DataLoader
from model import ReidentificationModel
from dataset import HAM1000Dataset
from logger import LoggerService
from datetime import datetime
from tqdm import tqdm
import time
import os
import random
def parse_arguments():
parser = argparse.ArgumentParser(
description='Medical Image Reidentification')
parser.add_argument('--em', type=int, default=128,
help='size of word embeddings')
parser.add_argument('--lr', type=float, default=0.05,
help='initial learning rate')
parser.add_argument('--epochs', type=int, default=20,
help='number of training epochs')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma')
parser.add_argument('--loss_margin', type=float, default=0.2,
help='Triplet loss margin')
parser.add_argument('--step_size', type=int, default=1,
help='Scheduler step size')
parser.add_argument('--batch_size', type=int, default=32,
help='batch size')
parser.add_argument('--seed', type=int, default=42,
help='random seed')
parser.add_argument('--log_interval', type=int, default=20,
help='report interval (in batches)')
args = parser.parse_args()
return args
def evaluate(model, dataset, criterion, device):
model.eval()
total_loss = 0.
with torch.no_grad():
for (anchor, positive, negative) in dataset:
anchor = anchor.to(device)
positive = positive.to(device)
negative = negative.to(device)
out_anchor, out_positive, out_negative = model(
anchor, positive, negative)
loss = criterion(out_anchor, out_positive, out_negative)
total_loss += loss.item()
return total_loss / len(dataset)
def train_step(model, dataset, criterion, optimizer, device, epoch, logger, log_interval):
model.train()
total_loss = 0.
for batch, (anchor, positive, negative) in enumerate(tqdm(dataset)):
optimizer.zero_grad()
anchor = anchor.to(device)
positive = positive.to(device)
negative = negative.to(device)
out_anchor, out_positive, out_negative = model(
anchor, positive, negative)
loss = criterion(out_anchor, out_positive, out_negative)
logger.log({"Training Item Loss": loss.item()})
loss.backward()
optimizer.step()
total_loss += loss.item()
if batch % log_interval == 0 and batch > 0:
avg_loss = total_loss / log_interval
total_batches = len(dataset)
print(
f'Epoch {epoch} | {batch}/{total_batches} batches | avg. loss {avg_loss:5.2f}')
logger.log({"Training Avg Loss": avg_loss})
total_loss = 0
def get_run_config_dict(args):
config = {
'epochs': args.epochs,
'batch_size': args.batch_size,
'embedding_size': args.em,
'learning_rate': args.lr,
'gamma': args.gamma,
'step_size': args.step_size
}
return config
def main():
args = parse_arguments()
SEED = args.seed
EMBEDDING_SIZE = args.em
EPOCHS = args.epochs
LEARNING_RATE = args.lr
BATCH_SIZE = args.batch_size
LOG_INTERVAL = args.log_interval
GAMMA = args.gamma
STEP_SIZE = args.step_size
TRIPLET_LOSS_MARGIN = args.loss_margin
torch.manual_seed(SEED)
np.random.seed(SEED)
random.seed(SEED)
model_config = get_run_config_dict(args)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_dataset = HAM1000Dataset('./dataset/HAM10000', split='train')
test_dataset = HAM1000Dataset('./dataset/HAM10000', split='test')
val_dataset = HAM1000Dataset('./dataset/HAM10000', split='val')
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE)
test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE)
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE)
model = ReidentificationModel(EMBEDDING_SIZE).to(device)
optimizer = optim.Adagrad(model.parameters(), lr=LEARNING_RATE)
scheduler = optim.lr_scheduler.StepLR(
optimizer, step_size=STEP_SIZE, gamma=GAMMA)
criterion = nn.TripletMarginLoss(margin=TRIPLET_LOSS_MARGIN)
logger = LoggerService(use_wandb=False)
logger.initialize(model, model_config, None)
best_validation_loss = None
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
model_directory = os.path.join(
'models', f'model_{timestamp}_{EMBEDDING_SIZE}em')
os.makedirs(model_directory)
try:
for epoch in range(1, EPOCHS + 1):
print(f'Training epoch {epoch} out of {EPOCHS}...')
logger.log({"Epoch": epoch})
epoch_start_time = time.time()
train_step(model, train_loader, criterion,
optimizer, device, epoch, logger, LOG_INTERVAL)
validation_loss = evaluate(model, val_loader, criterion, device)
elapsed_time = time.time() - epoch_start_time
print('-' * 89)
print(
f'Finished epoch {epoch} | elapsed: {elapsed_time:5.2f}s | validation loss {validation_loss:5.2f}')
print('-' * 89)
logger.log({"Validation Loss": validation_loss})
if best_validation_loss is None or validation_loss < best_validation_loss:
model_path = os.path.join(
model_directory, f'model_{epoch}.pth')
with open(model_path, 'wb') as f:
torch.save(model, f)
best_validation_loss = validation_loss
logger.log({"Epoch": epoch})
scheduler.step()
except KeyboardInterrupt:
print('Stopped training...')
print('Finished training! Evaluating model on testing dataset...')
test_loss = evaluate(model, test_loader, criterion, device)
print(
f'Finished testing! Test loss: {test_loss:.2f}')
logger.log({"Test Final Loss": test_loss})
logger.finish()
if __name__ == '__main__':
main()