프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / WebServer / symbol_training / train.py @ 8c26ccb2

이력 | 보기 | 이력해설 | 다운로드 (12.2 KB)

1
"""
2
Training For Small Object
3
"""
4
import os
5
import argparse
6
import torch.nn as nn
7
from torch.utils.data import DataLoader
8
from src.doftech_dataset import DoftechDataset, DoftechDatasetTest
9
from src.utils import *
10
from src.loss import YoloLoss
11
from src.yolo_net import Yolo
12
from src.yolo_doftech import YoloD
13
import shutil
14
import visdom
15
import cv2
16
import pickle
17
import numpy as np
18
from src.vis_utils import array_tool as at
19
from src.vis_utils.vis_tool import visdom_bbox
20

    
21
loss_data = {'X': [], 'Y': [], 'legend_U':['total', 'coord', 'conf', 'cls']}
22
#visdom = visdom.Visdom(port='8080')
23

    
24
# 형상 CLASS
25
DOFTECH_CLASSES= ['gate', 'globe', 'butterfly', 'check', 'ball', 'relief',
26
                  '3way_solenoid', 'gate_pressure', 'globe_pressure', 'butterfly_pressure', 'ball_shutoff', 'ball_pressure','ball_motor', 'plug_pressure',
27
                  'circle', 'inst_console', 'inst_console_dcs', 'inst_console_sih', 'logic_dcs', 'utility', 'specialty_items', 'logic', 'logic_local_console_dcs',
28
                  'reducer', 'blind_spectacle_open', 'blind_insertion_open', 'blind_spectacle_close', 'blind_insertion_close',
29
                  'strainer_basket', 'strainer_conical', 'fitting_capillary_tubing', 'meter_ultrasonic', 'strainer_y', 'tube_pitot'
30
                  ,'opc']
31

    
32
#print(len(DOFTECH_CLASSES))
33

    
34
def train(name=None, classes=None, root_path=None, pre_trained_model_path=None):
35
    global DOFTECH_CLASSES
36
    DOFTECH_CLASSES = classes
37

    
38
    parser = argparse.ArgumentParser("You Only Look Once: Unified, Real-Time Object Detection")
39
    parser.add_argument("--image_size", type=int, default=512, help="The common width and height for all images")
40
    parser.add_argument("--batch_size", type=int, default=10, help="The number of images per batch")
41

    
42
    # Training 기본 Setting
43
    parser.add_argument("--momentum", type=float, default=0.9)
44
    parser.add_argument("--decay", type=float, default=0.0005)
45
    parser.add_argument("--dropout", type=float, default=0.5)
46
    parser.add_argument("--num_epoches", type=int, default=205)
47
    parser.add_argument("--test_interval", type=int, default=20, help="Number of epoches between testing phases")
48
    parser.add_argument("--object_scale", type=float, default=1.0)
49
    parser.add_argument("--noobject_scale", type=float, default=0.5)
50
    parser.add_argument("--class_scale", type=float, default=1.0)
51
    parser.add_argument("--coord_scale", type=float, default=5.0)
52
    parser.add_argument("--reduction", type=int, default=32)
53
    parser.add_argument("--es_min_delta", type=float, default=0.0,
54
                        help="Early stopping's parameter: minimum change loss to qualify as an improvement")
55
    parser.add_argument("--es_patience", type=int, default=0,
56
                        help="Early stopping's parameter: number of epochs with no improvement after which training will be stopped. Set to 0 to disable this technique.")
57

    
58
    # 확인해야 하는 PATH
59
    parser.add_argument("--data_path", type=str, default=os.path.join(root_path, 'training'), help="the root folder of dataset") # 학습 데이터 경로 -> image와 xml의 상위 경로 입력
60
    parser.add_argument("--data_path_test", type=str, default=os.path.join(root_path, 'test'), help="the root folder of dataset") # 테스트 데이터 경로 -> test할 이미지만 넣으면 됨
61
    #parser.add_argument("--pre_trained_model_type", type=str, choices=["model", "params"], default="model")
62
    parser.add_argument("--pre_trained_model_path", type=str, default=pre_trained_model_path) # Pre-training 된 모델 경로
63

    
64
    parser.add_argument("--saved_path", type=str, default=os.path.join(root_path, 'checkpoint')) # training 된 모델 저장 경로
65
    parser.add_argument("--conf_threshold", type=float, default=0.35)
66
    parser.add_argument("--nms_threshold", type=float, default=0.5)
67
    opt = parser.parse_args()
68

    
69
    if not os.path.isdir(opt.saved_path):
70
        os.mkdir(save_dir)
71

    
72
    with open(os.path.join(opt.saved_path, name + "_info.info"), 'w') as stream:
73
        con = str(len(DOFTECH_CLASSES))
74
        names = '\n'.join(DOFTECH_CLASSES)
75
        con = con + '\n' + names
76
        stream.write(con)
77

    
78
    if torch.cuda.is_available():
79
        torch.cuda.manual_seed(123)
80
    else:
81
        torch.manual_seed(123)
82
    learning_rate_schedule = {"0": 1e-5, "5": 1e-4,
83
                              "80": 1e-5, "110": 1e-6}
84

    
85
    training_params = {"batch_size": opt.batch_size,
86
                       "shuffle": True,
87
                       "drop_last": True,
88
                       "collate_fn": custom_collate_fn}
89

    
90
    test_params = {"batch_size": opt.batch_size,
91
                   "shuffle": False,
92
                   "drop_last": False,
93
                   "collate_fn": custom_collate_fn}
94

    
95
    training_set = DoftechDataset(opt.data_path, opt.image_size, is_training=True, classes=DOFTECH_CLASSES)
96
    training_generator = DataLoader(training_set, **training_params)
97

    
98
    test_set = DoftechDatasetTest(opt.data_path_test, opt.image_size, is_training=False, classes=DOFTECH_CLASSES)
99
    test_generator = DataLoader(test_set, **test_params)
100

    
101
    pre_model = Yolo(20).cuda()
102
    pre_model.load_state_dict(torch.load(opt.pre_trained_model_path), strict=False)
103

    
104
    model = YoloD(pre_model, training_set.num_classes).cuda()
105

    
106
    nn.init.normal_(list(model.modules())[-1].weight, 0, 0.01)
107

    
108
    criterion = YoloLoss(training_set.num_classes, model.anchors, opt.reduction)
109
    optimizer = torch.optim.SGD(model.parameters(), lr=1e-5, momentum=opt.momentum, weight_decay=opt.decay)
110

    
111
    best_loss = 1e10
112
    best_epoch = 0
113
    model.train()
114
    num_iter_per_epoch = len(training_generator)
115

    
116
    loss_step = 0
117

    
118
    save_count = 0
119

    
120
    for epoch in range(opt.num_epoches):
121
        if str(epoch) in learning_rate_schedule.keys():
122
            for param_group in optimizer.param_groups:
123
                param_group['lr'] = learning_rate_schedule[str(epoch)]
124

    
125
        for iter, batch in enumerate(training_generator):
126
            image, label = batch
127
            if torch.cuda.is_available():
128
                image = Variable(image.cuda(), requires_grad=True)
129
            else:
130
                image = Variable(image, requires_grad=True)
131

    
132
            optimizer.zero_grad()
133
            logits = model(image)
134
            loss, loss_coord, loss_conf, loss_cls = criterion(logits, label)
135
            loss.backward()
136

    
137
            optimizer.step()
138

    
139
            if iter % opt.test_interval == 0:
140
                print("Epoch: {}/{}, Iteration: {}/{}, Lr: {}, Loss:{:.5f} (Coord:{:.5f} Conf:{:.5f} Cls:{:.5f})".format
141
                    (epoch + 1, opt.num_epoches, iter + 1, num_iter_per_epoch, optimizer.param_groups[0]['lr'], loss,
142
                    loss_coord,loss_conf,loss_cls))
143

    
144
                predictions = post_processing(logits, opt.image_size, DOFTECH_CLASSES, model.anchors, opt.conf_threshold,
145
                                              opt.nms_threshold)
146

    
147
                gt_image = at.tonumpy(image[0])
148
                gt_image = visdom_bbox(gt_image, label[0])
149
                #visdom.image(gt_image, opts=dict(title='gt_box_image'), win=3)
150

    
151
                if len(predictions) != 0:
152
                    image = at.tonumpy(image[0])
153
                    box_image = visdom_bbox(image, predictions[0])
154
                    #visdom.image(box_image, opts=dict(title='box_image'), win=2)
155

    
156
                elif len(predictions) == 0:
157
                    box_image = tensor2im(image)
158
                    #visdom.image(box_image.transpose([2, 0, 1]), opts=dict(title='box_image'), win=2)
159

    
160
                loss_dict = {
161
                    'total' : loss.item(),
162
                    'coord' : loss_coord.item(),
163
                    'conf' : loss_conf.item(),
164
                    'cls' : loss_cls.item()
165
                }
166

    
167
                #visdom_loss(visdom, loss_step, loss_dict)
168
                loss_step = loss_step + 1
169

    
170
        if epoch % opt.test_interval == 0:
171
            model.eval()
172
            loss_ls = []
173
            loss_coord_ls = []
174
            loss_conf_ls = []
175
            loss_cls_ls = []
176
            for te_iter, te_batch in enumerate(test_generator):
177
                te_image, te_label = te_batch
178
                num_sample = len(te_label)
179
                if torch.cuda.is_available():
180
                    te_image = te_image.cuda()
181
                with torch.no_grad():
182
                    te_logits = model(te_image)
183
                    batch_loss, batch_loss_coord, batch_loss_conf, batch_loss_cls = criterion(te_logits, te_label)
184
                loss_ls.append(batch_loss * num_sample)
185
                loss_coord_ls.append(batch_loss_coord * num_sample)
186
                loss_conf_ls.append(batch_loss_conf * num_sample)
187
                loss_cls_ls.append(batch_loss_cls * num_sample)
188

    
189
            te_loss = sum(loss_ls) / test_set.__len__()
190
            te_coord_loss = sum(loss_coord_ls) / test_set.__len__()
191
            te_conf_loss = sum(loss_conf_ls) / test_set.__len__()
192
            te_cls_loss = sum(loss_cls_ls) / test_set.__len__()
193
            print("Test>> Epoch: {}/{}, Lr: {}, Loss:{:.5f} (Coord:{:.5f} Conf:{:.5f} Cls:{:.5f})".format(
194
                epoch + 1, opt.num_epoches, optimizer.param_groups[0]['lr'], te_loss, te_coord_loss, te_conf_loss, te_cls_loss))
195

    
196
            model.train()
197
            if te_loss + opt.es_min_delta < best_loss:
198
                save_count += 1
199
                best_loss = te_loss
200
                best_epoch = epoch
201
                print("SAVE MODEL")
202
                # for debug for each loss
203
                torch.save(model.state_dict(), os.path.join(opt.saved_path, name + "_only_params_" + str(save_count) + "_" + "{:.5f}".format(best_loss) + ".pth"))
204
                torch.save(model, os.path.join(opt.saved_path, name + "_whole_model_" + str(save_count) + "_" + "{:.5f}".format(best_loss) + ".pth"))
205
                # save
206
                torch.save(model.state_dict(), os.path.join(opt.saved_path, name + "_only_params.pth"))
207
                torch.save(model, os.path.join(opt.saved_path, name + "_whole_model.pth"))
208

    
209
            # Early stopping
210
            if epoch - best_epoch > opt.es_patience > 0:
211
                print("Stop training at epoch {}. The lowest loss achieved is {}".format(epoch, te_loss))
212
                break
213

    
214
def visdom_loss(visdom, loss_step, loss_dict):
215
    loss_data['X'].append(loss_step)
216
    loss_data['Y'].append([loss_dict[k] for k in loss_data['legend_U']])
217
    visdom.line(
218
        X=np.stack([np.array(loss_data['X'])] * len(loss_data['legend_U']), 1),
219
        Y=np.array(loss_data['Y']),
220
        win=30,
221
        opts=dict(xlabel='Step',
222
                  ylabel='Loss',
223
                  title='YOLO_V2',
224
                  legend=loss_data['legend_U']),
225
        update='append'
226
    )
227

    
228
def tensor2im(image_tensor, imtype=np.uint8):
229

    
230
    image_numpy = image_tensor[0].detach().cpu().float().numpy()
231

    
232
    image_numpy = (np.transpose(image_numpy, (1, 2, 0)))
233

    
234
    image_numpy = np.clip(image_numpy, 0, 255)
235

    
236
    return image_numpy.astype(imtype)
237

    
238
def denormalize(tensors):
239
    """ Denormalizes image tensors using mean and std """
240
    mean = np.array([0.5, 0.5, 0.5])
241
    std = np.array([0.5, 0.5, 0.5])
242

    
243
    # mean = np.array([0.47571, 0.50874, 0.56821])
244
    # std = np.array([0.10341, 0.1062, 0.11548])
245

    
246
    denorm = tensors.clone()
247

    
248
    for c in range(tensors.shape[1]):
249
        denorm[:, c] = denorm[:, c].mul_(std[c]).add_(mean[c])
250

    
251
    denorm = torch.clamp(denorm, 0, 255)
252

    
253
    return denorm
254

    
255
if __name__ == "__main__":
256
    datas = ['gate', 'globe', 'butterfly', 'check', 'ball', 'relief',
257
                  '3way_solenoid', 'gate_pressure', 'globe_pressure', 'butterfly_pressure', 'ball_shutoff', 'ball_pressure','ball_motor', 'plug_pressure',
258
                  'inst', 'func_valve', 'inst_console', 'inst_console_dcs', 'inst_console_sih', 'logic_dcs', 'utility', 'specialty_items', 'logic', 'logic_local_console_dcs',
259
                  'reducer', 'blind_spectacle_open', 'blind_insertion_open', 'blind_spectacle_close', 'blind_insertion_close',
260
                  'strainer_basket', 'strainer_conical', 'fitting_capillary_tubing', 'meter_ultrasonic', 'strainer_y', 'tube_pitot',
261
                  'opc']
262
    data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)) + '\\Data\\', 'VnV')
263
    train(name='VnV', classes=datas, root_path=data_path, pre_trained_model_path=os.path.dirname(os.path.realpath(
264
                                                       __file__)) + '\\pre_trained_model\\only_params_trained_yolo_voc')
클립보드 이미지 추가 (최대 크기: 500 MB)