-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
195 lines (173 loc) · 8.58 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
# installed imports
import torchmetrics.detection.mean_ap
import torch.utils.data as data_utils
from torch.utils.tensorboard import SummaryWriter
import matplotlib.pyplot as plt
import torch
# default imports
from datetime import datetime as time
# local imports
from dataloader import BoardDetectorDataset, PieceDetectorDataset, PieceDetectorCOGDataset, PieceDetectorDatasetDB
from models import BoardDetector, PieceDetector
from trainers import train_board_detector, train_piece_detector
from helpers import *
device = "cpu"
if torch.cuda.is_available():
print('running cuda...')
device = "cuda"
elif torch.backends.mps.is_available():
print('running mps...')
device = "mps"
def main():
"""
PIECE DETECTOR TRAINING SECTION
"""
img_size = 320
MODEL = f'{img_size}_faster_rcnn'
# loads from local dir
# json_file = 'dataloader/data/piece_detection_coco.json'
# root_folder = 'dataloader/data/raw/'
# loads from d drive
root_folder = "d:/Projects/Chess Detection Data/data_generation/data/images"
ann_file = "d:/Projects/Chess Detection Data/data_generation/data/annotations.db"
# limiting the dataset to promote overfitting
# LIMIT = 100
# overfit_dataset = data_utils.Subset(PieceDetectorDatasetDB(root_folder, ann_file), list(range(0, LIMIT)))
dataset = PieceDetectorDatasetDB(root_folder, ann_file)
PRETRAINED = True
epochs = 2
batch_size = [4]
lr = [1e-4]
weight_decay = 0.0005
# writer = SummaryWriter(f'models/checkpoints/piece_detector/{MODEL}/tensorboard_overfit')
for b in batch_size:
for l in lr:
loss, lowest_loss, m_ap = train_piece_detector(batch_size=b, # hyperparameter search (batch_size)
epochs=epochs,
# load=f'models/checkpoints/piece_detector/{MODEL}/synthetic_overfit',
# save=f'models/checkpoints/piece_detector/{MODEL}/synthetic_overfit',
img_size=(img_size, img_size),
learning_rate=l, # hyperparameter search (learning_rate)
weight_decay=weight_decay,
from_pretrained=PRETRAINED,
mixed_precision_training=torch.cuda.is_available(),
# writer=writer, # optional summary writer added!
step=2500,
device=device,
dataset=dataset)
# writer.add_hparams({'learning rate': l, 'batch size': b},
# {'lowest loss': lowest_loss, 'last loss': loss, 'mAP': m_ap['map']})
# writer.close()
print('Training Complete!')
"""
PIECE DETECTOR VIEW OUTPUT
"""
# weights = f'models/checkpoints/piece_detector/{MODEL}/final/synthetic_weight_16_0.0001'
# piece_detector = PieceDetector(pretrained=PRETRAINED).to(device)
# piece_detector.load_state_dict(torch.load(weights, map_location=device))
# piece_detector.eval()
# piece_data = PieceDetectorDataset(root=root_folder, json_file=json_file, size=(img_size, img_size))
# img, _ = piece_data[4]
# features = piece_detector.detector.backbone(img.unsqueeze(0).to(device))
# save_location = 'dataloader/data/trained_fpn_output/80x80'
# for i, feature in tqdm(enumerate(features['0'][0])):
# plt.imshow(feature.detach().numpy())
# plt.axis('off')
# plt.gca().set_axis_off()
# plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
# plt.margins(0, 0)
# plt.gca().xaxis.set_major_locator(plt.NullLocator())
# plt.gca().yaxis.set_major_locator(plt.NullLocator())
# plt.savefig(f'{save_location}/{i}.jpg', bbox_inches='tight', pad_inches=0)
# f, ax = plt.subplots(1, 5, figsize=(12, 5))
# ax[0].imshow(features['0'][0][0].detach().numpy())
# ax[1].imshow(features['1'][0][0].detach().numpy())
# ax[2].imshow(features['2'][0][0].detach().numpy())
# ax[3].imshow(features['3'][0][0].detach().numpy())
# ax[4].imshow(features['pool'][0][0].detach().numpy())
# plt.show()
# img, target = piece_data[0]
# targets = [{k: v.to(device) for k, v in target.items()}]
# preds = piece_detector(img.unsqueeze(0).to(device))
# mAP = torchmetrics.detection.mean_ap.MeanAveragePrecision()
# mAP.update(preds, targets)
# out = mAP.compute()
# print(out)
# idx = 0
# while idx < len(piece_data):
# show_piece_detector_results(idx, piece_detector, piece_data, device)
# try:
# idx += 1
# except:
# quit()
# show_piece_detector_results(12, piece_detector, piece_data, device)
"""
BOARD DETECTOR TRAINING SECTION
"""
# img_size = 320
# MODEL = 'resnet'
# json_file = 'dataloader/data/data_generation/images/board_coco.json'
# root_folder = 'dataloader/data/data_generation/images/'
# PRETRAINED = True
# epochs = 10
# batch_size = [16]
# lr = [1e-4]
# writer = SummaryWriter(f'models/checkpoints/board_detector/{MODEL}/tensorboard')
# step= 0
# last_loss = 0
# lowest_loss = 0
# for b in batch_size:
# for l in lr:
# print(f'currently training for (batch_size: {b}, lr: {l})')
# last_loss, lowest_loss = train_board_detector(model=MODEL,
# epochs=epochs,
# batch_size=b,
# learning_rate=l,
# mixed_precision_training=torch.cuda.is_available(),
# load=None,
# save=f'models/checkpoints/board_detector/{MODEL}/weight_{b}_{l}',
# json_file=json_file,
# root_folder=root_folder,
# from_pretrained=PRETRAINED,
# writer=writer,
# step=step,
# device=device)
# # writer.add_hparams({'batch size': b, 'learning rate': l}, {'last_loss': last_loss, 'lowest_loss': lowest_loss})
# writer.close()
# print(f'last:{last_loss} lowest:{lowest_loss}')
# print('Training Complete!')
"""
BOARD DETECTOR VIEW OUTPUT
"""
# weights = f'models/checkpoints/board_detector/{MODEL}/weight'
#
# board_detector = BoardDetector(model=MODEL).to(device)
# board_detector.load_state_dict(torch.load(weights, map_location=device))
# board_detector.eval()
# board_data = BoardDetectorDataset(root_folder, json_file, size=320, target="points")
#
# tr = transforms.Compose([transforms.Resize(img_size)])
# img_path = 'dataloader/data/raw/IMG_0624.jpg'
# img = tr(read_image(img_path) / 255.0)
# img = img.unsqueeze(0).to(device)
# points = board_detector(img) * img_size
# warped_img, _ = warp(img, reshape_coords(points), device=device)
# fig, ax = plt.subplots(1, 2)
# points = points[0].view(4, 2).transpose(0, 1)
# ax[0].imshow(img[0].cpu().permute(1, 2, 0))
# ax[0].scatter(points[0].detach().cpu(), points[1].detach().cpu())
# ax[1].imshow(warped_img[0].detach().cpu().permute(1, 2, 0))
# plt.show()
# for i in range(len(board_data)):
# img, _ = board_data[i]
# img = img.unsqueeze(0).to(device)
# points = board_detector(img) * img_size
# warped_img, _ = warp(img, reshape_coords(points), device=device)
# fig, ax = plt.subplots(1, 2)
# points = points[0].view(4, 2).transpose(0, 1)
# ax[0].imshow(img[0].cpu().permute(1, 2, 0))
# ax[0].scatter(points[0].detach().cpu(), points[1].detach().cpu())
# ax[1].imshow(warped_img[0].detach().cpu().permute(1, 2, 0))
# plt.show()
if __name__ == '__main__':
main()