-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
212 lines (163 loc) · 7.91 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
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
import argparse
import os
import time
import matplotlib.pyplot as plt
import torch
from torch.optim import SGD
from torchvision import utils
from utils import create_dataloader, YOLOv1Loss, parse_cfg, build_model
# from torchviz import make_dot
def train(model, train_loader, optimizer, epoch, device, S, B, train_loss_lst, output_path):
model.train() # Set the module in training mode
train_loss = 0
for batch_idx, (inputs, labels) in enumerate(train_loader):
t_start = time.time()
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
# back prop
criterion = YOLOv1Loss(S, B)
optimizer.zero_grad()
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
t_batch = time.time() - t_start
# show batch0 dataset
if batch_idx == 0 and epoch == 0:
fig = plt.figure()
inputs = inputs.cpu() # convert to cpu
grid = utils.make_grid(inputs)
plt.imshow(grid.numpy().transpose((1, 2, 0)))
plt.savefig(os.path.join(output_path, 'batch0.png'))
# plt.show()
plt.close(fig)
# print loss and accuracy
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.1f}%)] Time: {:.4f}s Loss: {:.6f}'
.format(epoch, batch_idx * len(inputs), len(train_loader.dataset),
100. * batch_idx / len(train_loader), t_batch, loss.item()))
# record training loss
train_loss /= len(train_loader)
train_loss_lst.append(train_loss)
return train_loss_lst
def validate(model, val_loader, device, S, B, val_loss_lst):
model.eval() # Sets the module in evaluation mode
val_loss = 0
# no need to calculate gradients
with torch.no_grad():
for data, target in val_loader:
data, target = data.to(device), target.to(device)
output = model(data)
# add one batch loss
criterion = YOLOv1Loss(S, B)
val_loss += criterion(output, target).item()
val_loss /= len(val_loader)
print('Val set: Average loss: {:.4f}\n'.format(val_loss))
# record validating loss
val_loss_lst.append(val_loss)
return val_loss_lst
def test(model, test_loader, device, S, B):
model.eval() # Sets the module in evaluation mode
test_loss = 0
# no need to calculate gradients
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
# add one batch loss
criterion = YOLOv1Loss(S, B)
test_loss += criterion(output, target).item()
# record testing loss
test_loss /= len(test_loader)
print('Test set: Average loss: {:.4f}'.format(test_loss))
def main(cfg="cfg/yolov1.yaml", dataset_cfg="cfg/dataset.yaml", weights="", output="output", epochs=100, lr=0.002, batch_size=32, save_freq=10):
# create output file folder
start = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
output_path = os.path.join(output, start)
os.makedirs(output_path)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# build model
torch.manual_seed(1)
model = build_model(weights, S, B, num_classes).to(device)
# get data loader
train_loader, val_loader, test_loader = create_dataloader(img_path, label_path, 0.8, 0.1, 0.1, batch_size,
input_size, S, B, num_classes)
optimizer = SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=0.0005)
# optimizer = Adam(model.parameters(), lr=lr)
train_loss_lst, val_loss_lst = [], []
# train epoch
for epoch in range(epochs):
train_loss_lst = train(model, train_loader, optimizer, epoch, device, S, B, train_loss_lst, output_path)
val_loss_lst = validate(model, val_loader, device, S, B, val_loss_lst)
# save model weight every save_freq epoch
if epoch % save_freq == 0 and epoch >= epochs / 2:
torch.save(model.state_dict(), os.path.join(output_path, 'epoch' + str(epoch) + '.pth'))
test(model, test_loader, device, S, B)
# save model
torch.save(model.state_dict(), os.path.join(output_path, 'last.pth'))
# plot loss, save params change
fig = plt.figure()
plt.plot(range(epochs), train_loss_lst, 'g', label='train loss')
plt.plot(range(epochs), val_loss_lst, 'k', label='val loss')
plt.grid(True)
plt.xlabel('epoch')
plt.ylabel('acc-loss')
plt.legend(loc="upper right")
plt.savefig(os.path.join(output_path, 'loss_curve.jpg'))
plt.show()
plt.close(fig)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='YOLOv1-pytorch')
parser.add_argument("--cfg", "-c", default="cfg/yolov1.yaml", help="Yolov1 config file path", type=str)
parser.add_argument("--dataset_cfg", "-d", default="cfg/dataset.yaml", help="Dataset config file path", type=str)
parser.add_argument("--weights", "-w", default="", help="Pretrained model weights path", type=str)
parser.add_argument("--output", "-o", default="output", help="Output path", type=str)
parser.add_argument("--epochs", "-e", default=100, help="Training epochs", type=int)
parser.add_argument("--lr", "-lr", default=0.002, help="Training learning rate", type=float)
parser.add_argument("--batch_size", "-bs", default=32, help="Training batch size", type=int)
parser.add_argument("--save_freq", "-sf", default=10, help="Frequency of saving model checkpoint when training",
type=int)
args = parser.parse_args()
cfg = parse_cfg(args.cfg)
dataset_cfg = parse_cfg(args.dataset_cfg)
img_path, label_path = dataset_cfg['images'], dataset_cfg['labels']
S, B, num_classes, input_size = cfg['S'], cfg['B'], cfg['num_classes'], cfg['input_size']
# create output file folder
start = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
output_path = os.path.join(args.output, start)
os.makedirs(output_path)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# build model
torch.manual_seed(1)
model = build_model(args.weights, S, B, num_classes).to(device)
# plot model structure
# graph = make_dot(model(torch.rand(1, 3, args.input_size, args.input_size).cuda()),
# params=dict(model.named_parameters()))
# graph.render('model_structure', './', cleanup=True, format='png')
# get data loader
train_loader, val_loader, test_loader = create_dataloader(img_path, label_path, 0.8, 0.1, 0.1, args.batch_size,
input_size, S, B, num_classes)
optimizer = SGD(model.parameters(), lr=args.lr, momentum=0.9, weight_decay=0.0005)
# optimizer = Adam(model.parameters(), lr=lr)
train_loss_lst, val_loss_lst = [], []
# train epoch
for epoch in range(args.epochs):
train_loss_lst = train(model, train_loader, optimizer, epoch, device, S, B, train_loss_lst, output_path)
val_loss_lst = validate(model, val_loader, device, S, B, val_loss_lst)
# save model weight every save_freq epoch
if epoch % args.save_freq == 0 and epoch >= args.epochs / 2:
torch.save(model.state_dict(), os.path.join(output_path, 'epoch' + str(epoch) + '.pth'))
test(model, test_loader, device, S, B)
# save model
torch.save(model.state_dict(), os.path.join(output_path, 'last.pth'))
# plot loss, save params change
fig = plt.figure()
plt.plot(range(args.epochs), train_loss_lst, 'g', label='train loss')
plt.plot(range(args.epochs), val_loss_lst, 'k', label='val loss')
plt.grid(True)
plt.xlabel('epoch')
plt.ylabel('acc-loss')
plt.legend(loc="upper right")
plt.savefig(os.path.join(output_path, 'loss_curve.jpg'))
plt.show()
plt.close(fig)