-
Notifications
You must be signed in to change notification settings - Fork 15
/
train.py
128 lines (108 loc) · 3.96 KB
/
train.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
import torch
import os
import numpy as np
from tqdm import tqdm
from datetime import datetime
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from data import YoloPascalVocDataset
from loss import SumSquaredErrorLoss
from models import *
if __name__ == '__main__': # Prevent recursive subprocess creation
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.autograd.set_detect_anomaly(True) # Check for nan loss
writer = SummaryWriter()
now = datetime.now()
model = YOLOv1ResNet().to(device)
loss_function = SumSquaredErrorLoss()
# Adam works better
# optimizer = torch.optim.SGD(
# model.parameters(),
# lr=config.LEARNING_RATE,
# momentum=0.9,
# weight_decay=5E-4
# )
optimizer = torch.optim.Adam(
model.parameters(),
lr=config.LEARNING_RATE
)
# Learning rate scheduler (NOT NEEDED)
# scheduler = torch.optim.lr_scheduler.LambdaLR(
# optimizer,
# lr_lambda=utils.scheduler_lambda
# )
# Load the dataset
train_set = YoloPascalVocDataset('train', normalize=True, augment=True)
test_set = YoloPascalVocDataset('test', normalize=True, augment=True)
train_loader = DataLoader(
train_set,
batch_size=config.BATCH_SIZE,
num_workers=8,
persistent_workers=True,
drop_last=True,
shuffle=True
)
test_loader = DataLoader(
test_set,
batch_size=config.BATCH_SIZE,
num_workers=8,
persistent_workers=True,
drop_last=True
)
# Create folders
root = os.path.join(
'models',
'yolo_v1',
now.strftime('%m_%d_%Y'),
now.strftime('%H_%M_%S')
)
weight_dir = os.path.join(root, 'weights')
if not os.path.isdir(weight_dir):
os.makedirs(weight_dir)
# Metrics
train_losses = np.empty((2, 0))
test_losses = np.empty((2, 0))
train_errors = np.empty((2, 0))
test_errors = np.empty((2, 0))
def save_metrics():
np.save(os.path.join(root, 'train_losses'), train_losses)
np.save(os.path.join(root, 'test_losses'), test_losses)
np.save(os.path.join(root, 'train_errors'), train_errors)
np.save(os.path.join(root, 'test_errors'), test_errors)
#####################
# Train #
#####################
for epoch in tqdm(range(config.WARMUP_EPOCHS + config.EPOCHS), desc='Epoch'):
model.train()
train_loss = 0
for data, labels, _ in tqdm(train_loader, desc='Train', leave=False):
data = data.to(device)
labels = labels.to(device)
optimizer.zero_grad()
predictions = model.forward(data)
loss = loss_function(predictions, labels)
loss.backward()
optimizer.step()
train_loss += loss.item() / len(train_loader)
del data, labels
# Step and graph scheduler once an epoch
# writer.add_scalar('Learning Rate', scheduler.get_last_lr()[0], epoch)
# scheduler.step()
train_losses = np.append(train_losses, [[epoch], [train_loss]], axis=1)
writer.add_scalar('Loss/train', train_loss, epoch)
if epoch % 4 == 0:
model.eval()
with torch.no_grad():
test_loss = 0
for data, labels, _ in tqdm(test_loader, desc='Test', leave=False):
data = data.to(device)
labels = labels.to(device)
predictions = model.forward(data)
loss = loss_function(predictions, labels)
test_loss += loss.item() / len(test_loader)
del data, labels
test_losses = np.append(test_losses, [[epoch], [test_loss]], axis=1)
writer.add_scalar('Loss/test', test_loss, epoch)
save_metrics()
save_metrics()
torch.save(model.state_dict(), os.path.join(weight_dir, 'final'))