yolov3.py 19.7 KB
Newer Older
Y
Yang Zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import division
Y
Yang Zhang 已提交
16
from __future__ import print_function
Y
Yang Zhang 已提交
17 18 19 20 21 22 23

import argparse
import contextlib
import os
import random
import time

Y
Yang Zhang 已提交
24 25
from functools import partial

Y
Yang Zhang 已提交
26 27 28 29 30 31 32 33 34 35 36 37
import cv2
import numpy as np
from pycocotools.coco import COCO

import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Conv2D
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.regularizer import L2Decay

from model import Model, Loss, shape_hints
from resnet import ResNet, ConvBNLayer
D
dengkaipeng 已提交
38 39 40 41 42

import logging
FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)
Y
Yang Zhang 已提交
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


# XXX transfer learning
class ResNetBackBone(ResNet):
    def __init__(self, depth=50):
        super(ResNetBackBone, self).__init__(depth=depth)
        delattr(self, 'fc')

    def forward(self, inputs):
        x = self.conv(inputs)
        x = self.pool(x)
        outputs = []
        for layer in self.layers:
            x = layer(x)
            outputs.append(x)
        return outputs


class YoloDetectionBlock(fluid.dygraph.Layer):
    def __init__(self, num_channels, num_filters):
        super(YoloDetectionBlock, self).__init__()

        assert num_filters % 2 == 0, \
            "num_filters {} cannot be divided by 2".format(num_filters)

        self.conv0 = ConvBNLayer(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=1,
            act='leaky_relu')
        self.conv1 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters * 2,
            filter_size=3,
            act='leaky_relu')
        self.conv2 = ConvBNLayer(
            num_channels=num_filters * 2,
            num_filters=num_filters,
            filter_size=1,
            act='leaky_relu')
        self.conv3 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters * 2,
            filter_size=3,
            act='leaky_relu')
        self.route = ConvBNLayer(
            num_channels=num_filters * 2,
            num_filters=num_filters,
            filter_size=1,
            act='leaky_relu')
        self.tip = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters * 2,
            filter_size=3,
            act='leaky_relu')

    def forward(self, inputs):
        out = self.conv0(inputs)
        out = self.conv1(out)
        out = self.conv2(out)
        out = self.conv3(out)
        route = self.route(out)
        tip = self.tip(route)
        return route, tip


class YOLOv3(Model):
D
dengkaipeng 已提交
110
    def __init__(self, num_classes=80):
Y
Yang Zhang 已提交
111
        super(YOLOv3, self).__init__()
D
dengkaipeng 已提交
112
        self.num_classes = num_classes
Y
Yang Zhang 已提交
113 114 115 116
        self.anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45,
                        59, 119, 116, 90, 156, 198, 373, 326]
        self.anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
        self.valid_thresh = 0.005
D
dengkaipeng 已提交
117
        self.nms_thresh = 0.45
Y
Yang Zhang 已提交
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
        self.nms_topk = 400
        self.nms_posk = 100
        self.draw_thresh = 0.5

        self.backbone = ResNetBackBone()
        self.block_outputs = []
        self.yolo_blocks = []
        self.route_blocks = []

        for idx, num_chan in enumerate([2048, 1280, 640]):
            yolo_block = self.add_sublayer(
                "detecton_block_{}".format(idx),
                YoloDetectionBlock(num_chan, num_filters=512 // (2**idx)))
            self.yolo_blocks.append(yolo_block)

            num_filters = len(self.anchor_masks[idx]) * (self.num_classes + 5)

            block_out = self.add_sublayer(
                "block_out_{}".format(idx),
                Conv2D(num_channels=1024 // (2**idx),
                       num_filters=num_filters,
                       filter_size=1,
                       param_attr=ParamAttr(
                           initializer=fluid.initializer.Normal(0., 0.02)),
                       bias_attr=ParamAttr(
                           initializer=fluid.initializer.Constant(0.0),
                           regularizer=L2Decay(0.))))
            self.block_outputs.append(block_out)
            if idx < 2:
                route = self.add_sublayer(
                    "route_{}".format(idx),
                    ConvBNLayer(num_channels=512 // (2**idx),
                                num_filters=256 // (2**idx),
                                filter_size=1,
                                act='leaky_relu'))
                self.route_blocks.append(route)

D
dengkaipeng 已提交
155 156
    @shape_hints(inputs=[None, 3, None, None], img_info=[None, 3])
    def forward(self, inputs, img_info):
Y
Yang Zhang 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169
        outputs = []
        boxes = []
        scores = []
        downsample = 32

        feats = self.backbone(inputs)
        feats = feats[::-1][:len(self.anchor_masks)]
        route = None
        for idx, feat in enumerate(feats):
            if idx > 0:
                feat = fluid.layers.concat(input=[route, feat], axis=1)
            route, tip = self.yolo_blocks[idx](feat)
            block_out = self.block_outputs[idx](tip)
D
dengkaipeng 已提交
170
            outputs.append(block_out)
Y
Yang Zhang 已提交
171 172 173 174 175

            if idx < 2:
                route = self.route_blocks[idx](route)
                route = fluid.layers.resize_nearest(route, scale=2)

176
            if self.mode == 'test':
D
dengkaipeng 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                anchor_mask = self.anchor_masks[idx]
                mask_anchors = []
                for m in anchor_mask:
                    mask_anchors.append(self.anchors[2 * m])
                    mask_anchors.append(self.anchors[2 * m + 1])
                img_shape = fluid.layers.slice(img_info, axes=[1], starts=[1], ends=[3])
                img_id = fluid.layers.slice(img_info, axes=[1], starts=[0], ends=[1])
                b, s = fluid.layers.yolo_box(
                    x=block_out,
                    img_size=img_shape,
                    anchors=mask_anchors,
                    class_num=self.num_classes,
                    conf_thresh=self.valid_thresh,
                    downsample_ratio=downsample)

                boxes.append(b)
                scores.append(fluid.layers.transpose(s, perm=[0, 2, 1]))
Y
Yang Zhang 已提交
194 195 196

            downsample //= 2

197 198
        if self.mode != 'test':
            return outputs
Y
Yang Zhang 已提交
199

200
        return [img_id, fluid.layers.multiclass_nms(
Y
Yang Zhang 已提交
201 202 203 204 205 206
            bboxes=fluid.layers.concat(boxes, axis=1),
            scores=fluid.layers.concat(scores, axis=2),
            score_threshold=self.valid_thresh,
            nms_top_k=self.nms_topk,
            keep_top_k=self.nms_posk,
            nms_threshold=self.nms_thresh,
D
dengkaipeng 已提交
207
            background_label=-1)]
Y
Yang Zhang 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237


class YoloLoss(Loss):
    def __init__(self, num_classes=80, num_max_boxes=50):
        super(YoloLoss, self).__init__()
        self.num_classes = num_classes
        self.num_max_boxes = num_max_boxes
        self.ignore_thresh = 0.7
        self.anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45,
                        59, 119, 116, 90, 156, 198, 373, 326]
        self.anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]

    def forward(self, outputs, labels):
        downsample = 32
        gt_box, gt_label, gt_score = labels
        losses = []

        for idx, out in enumerate(outputs):
            anchor_mask = self.anchor_masks[idx]
            loss = fluid.layers.yolov3_loss(
                x=out,
                gt_box=gt_box,
                gt_label=gt_label,
                gt_score=gt_score,
                anchor_mask=anchor_mask,
                downsample_ratio=downsample,
                anchors=self.anchors,
                class_num=self.num_classes,
                ignore_thresh=self.ignore_thresh,
                use_label_smooth=True)
D
dengkaipeng 已提交
238
            loss = fluid.layers.reduce_mean(loss)
Y
Yang Zhang 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            losses.append(loss)
            downsample //= 2
        return losses

    def infer_shape(self, _):
        return [
            [None, self.num_max_boxes, 4],
            [None, self.num_max_boxes],
            [None, self.num_max_boxes]
        ]

    def infer_dtype(self, _):
        return ['float32', 'int32', 'float32']


def make_optimizer(parameter_list=None):
Y
Yang Zhang 已提交
255
    base_lr = FLAGS.lr
Y
Yang Zhang 已提交
256 257 258
    warm_up_iter = 4000
    momentum = 0.9
    weight_decay = 5e-4
Y
Yang Zhang 已提交
259
    boundaries = [400000, 450000]
Y
Yang Zhang 已提交
260
    values = [base_lr * (0.1 ** i) for i in range(len(boundaries) + 1)]
Y
Yang Zhang 已提交
261
    learning_rate = fluid.layers.piecewise_decay(
Y
Yang Zhang 已提交
262 263
        boundaries=boundaries,
        values=values)
Y
Yang Zhang 已提交
264 265
    learning_rate = fluid.layers.linear_lr_warmup(
        learning_rate=learning_rate,
Y
Yang Zhang 已提交
266 267 268 269
        warmup_steps=warm_up_iter,
        start_lr=0.0,
        end_lr=base_lr)
    optimizer = fluid.optimizer.Momentum(
Y
Yang Zhang 已提交
270
        learning_rate=learning_rate,
Y
Yang Zhang 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        regularization=fluid.regularizer.L2Decay(weight_decay),
        momentum=momentum,
        parameter_list=parameter_list)
    return optimizer


def _iou_matrix(a, b):
    tl_i = np.maximum(a[:, np.newaxis, :2], b[:, :2])
    br_i = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
    area_i = np.prod(br_i - tl_i, axis=2) * (tl_i < br_i).all(axis=2)
    area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
    area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)
    area_o = (area_a[:, np.newaxis] + area_b - area_i)
    return area_i / (area_o + 1e-10)


def _crop_box_with_center_constraint(box, crop):
    cropped_box = box.copy()
    cropped_box[:, :2] = np.maximum(box[:, :2], crop[:2])
    cropped_box[:, 2:] = np.minimum(box[:, 2:], crop[2:])
    cropped_box[:, :2] -= crop[:2]
    cropped_box[:, 2:] -= crop[:2]
    centers = (box[:, :2] + box[:, 2:]) / 2
    valid = np.logical_and(
        crop[:2] <= centers, centers < crop[2:]).all(axis=1)
    valid = np.logical_and(
        valid, (cropped_box[:, :2] < cropped_box[:, 2:]).all(axis=1))
    return cropped_box, np.where(valid)[0]


def random_crop(inputs):
    aspect_ratios = [.5, 2.]
    thresholds = [.0, .1, .3, .5, .7, .9]
    scaling = [.3, 1.]

D
dengkaipeng 已提交
306
    img, img_ids, gt_box, gt_label = inputs
Y
Yang Zhang 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    h, w = img.shape[:2]

    if len(gt_box) == 0:
        return inputs

    np.random.shuffle(thresholds)
    for thresh in thresholds:
        found = False
        for i in range(50):
            scale = np.random.uniform(*scaling)
            min_ar, max_ar = aspect_ratios
            ar = np.random.uniform(max(min_ar, scale**2),
                                   min(max_ar, scale**-2))
            crop_h = int(h * scale / np.sqrt(ar))
            crop_w = int(w * scale * np.sqrt(ar))
            crop_y = np.random.randint(0, h - crop_h)
            crop_x = np.random.randint(0, w - crop_w)
            crop_box = [crop_x, crop_y, crop_x + crop_w, crop_y + crop_h]
            iou = _iou_matrix(gt_box, np.array([crop_box], dtype=np.float32))
            if iou.max() < thresh:
                continue

            cropped_box, valid_ids = _crop_box_with_center_constraint(
                gt_box, np.array(crop_box, dtype=np.float32))
            if valid_ids.size > 0:
                found = True
                break

        if found:
            x1, y1, x2, y2 = crop_box
            img = img[y1:y2, x1:x2, :]
            gt_box = np.take(cropped_box, valid_ids, axis=0)
            gt_label = np.take(gt_label, valid_ids, axis=0)
D
dengkaipeng 已提交
340
            return img, img_ids, gt_box, gt_label
Y
Yang Zhang 已提交
341 342 343 344 345 346 347

        return inputs


# XXX mix up, color distort and random expand are skipped for simplicity
def sample_transform(inputs, mode='train', num_max_boxes=50):
    if mode == 'train':
D
dengkaipeng 已提交
348
        img, img_id, gt_box, gt_label = random_crop(inputs)
Y
Yang Zhang 已提交
349
    else:
D
dengkaipeng 已提交
350
        img, img_id, gt_box, gt_label = inputs
Y
Yang Zhang 已提交
351 352 353 354 355 356 357 358 359 360 361 362

    h, w = img.shape[:2]
    # random flip
    if mode == 'train' and np.random.uniform(0., 1.) > .5:
        img = img[:, ::-1, :]
        if len(gt_box) > 0:
            swap = gt_box.copy()
            gt_box[:, 0] = w - swap[:, 2] - 1
            gt_box[:, 2] = w - swap[:, 0] - 1

    if len(gt_label) == 0:
        gt_box = np.zeros([num_max_boxes, 4], dtype=np.float32)
D
dengkaipeng 已提交
363
        gt_label = np.zeros([num_max_boxes], dtype=np.int32)
Y
Yang Zhang 已提交
364 365 366 367 368 369 370 371 372 373 374
        return img, gt_box, gt_label

    gt_box = gt_box[:num_max_boxes, :]
    gt_label = gt_label[:num_max_boxes, 0]
    # normalize boxes
    gt_box /= np.array([w, h] * 2, dtype=np.float32)
    gt_box[:, 2:] = gt_box[:, 2:] - gt_box[:, :2]
    gt_box[:, :2] = gt_box[:, :2] + gt_box[:, 2:] / 2.

    pad = num_max_boxes - gt_label.size
    gt_box = np.pad(gt_box, ((0, pad), (0, 0)), mode='constant')
D
dengkaipeng 已提交
375
    gt_label = np.pad(gt_label, ((0, pad)), mode='constant')
Y
Yang Zhang 已提交
376

D
dengkaipeng 已提交
377
    return img, img_id, gt_box, gt_label
Y
Yang Zhang 已提交
378 379 380 381 382 383 384 385 386 387 388


def batch_transform(batch, mode='train'):
    if mode == 'train':
        d = np.random.choice(
            [320, 352, 384, 416, 448, 480, 512, 544, 576, 608])
        interp = np.random.choice(range(5))
    else:
        d = 608
        interp = cv2.INTER_CUBIC
    # transpose batch
D
dengkaipeng 已提交
389 390
    imgs, img_ids, gt_boxes, gt_labels = list(zip(*batch))
    img_shapes = np.array([[im.shape[0], im.shape[1]] for im in imgs]).astype('int32')
Y
Yang Zhang 已提交
391 392 393 394 395 396 397 398 399 400 401 402
    imgs = np.array([cv2.resize(
        img, (d, d), interpolation=interp) for img in imgs])

    # transpose, permute and normalize
    imgs = imgs.astype(np.float32)[..., ::-1]
    mean = np.array([123.675, 116.28, 103.53], dtype=np.float32)
    std = np.array([58.395, 57.120, 57.375], dtype=np.float32)
    invstd = 1. / std
    imgs -= mean
    imgs *= invstd
    imgs = imgs.transpose((0, 3, 1, 2))

D
dengkaipeng 已提交
403 404
    img_ids = np.array(img_ids)
    img_info = np.concatenate([img_ids, img_shapes], axis=1)
Y
Yang Zhang 已提交
405 406
    gt_boxes = np.array(gt_boxes)
    gt_labels = np.array(gt_labels)
Y
Yang Zhang 已提交
407
    # XXX since mix up is not used, scores are all ones
Y
Yang Zhang 已提交
408
    gt_scores = np.ones_like(gt_labels, dtype=np.float32)
D
dengkaipeng 已提交
409
    return [imgs, img_info], [gt_boxes, gt_labels, gt_scores]
Y
Yang Zhang 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448


def coco2017(root_dir, mode='train'):
    json_path = os.path.join(
        root_dir, 'annotations/instances_{}2017.json'.format(mode))
    coco = COCO(json_path)
    img_ids = coco.getImgIds()
    imgs = coco.loadImgs(img_ids)
    class_map = {v: i + 1 for i, v in enumerate(coco.getCatIds())}
    samples = []

    for img in imgs:
        img_path = os.path.join(
            root_dir, '{}2017'.format(mode), img['file_name'])
        file_path = img_path
        width = img['width']
        height = img['height']
        ann_ids = coco.getAnnIds(imgIds=img['id'], iscrowd=False)
        anns = coco.loadAnns(ann_ids)

        gt_box = []
        gt_label = []

        for ann in anns:
            x1, y1, w, h = ann['bbox']
            x2 = x1 + w - 1
            y2 = y1 + h - 1
            x1 = np.clip(x1, 0, width - 1)
            x2 = np.clip(x2, 0, width - 1)
            y1 = np.clip(y1, 0, height - 1)
            y2 = np.clip(y2, 0, height - 1)
            if ann['area'] <= 0 or x2 < x1 or y2 < y1:
                continue
            gt_label.append(ann['category_id'])
            gt_box.append([x1, y1, x2, y2])

        gt_box = np.array(gt_box, dtype=np.float32)
        gt_label = np.array([class_map[cls] for cls in gt_label],
                            dtype=np.int32)[:, np.newaxis]
D
dengkaipeng 已提交
449
        im_id = np.array([img['id']], dtype=np.int32)
Y
Yang Zhang 已提交
450 451 452

        if gt_label.size == 0 and not mode == 'train':
            continue
D
dengkaipeng 已提交
453
        samples.append((file_path, im_id.copy(), gt_box.copy(), gt_label.copy()))
Y
Yang Zhang 已提交
454 455 456

    def iterator():
        if mode == 'train':
D
dengkaipeng 已提交
457 458
            np.random.shuffle(samples)
        for file_path, im_id, gt_box, gt_label in samples:
Y
Yang Zhang 已提交
459
            img = cv2.imread(file_path)
D
dengkaipeng 已提交
460
            yield img, im_id, gt_box, gt_label
Y
Yang Zhang 已提交
461 462 463 464 465 466

    return iterator


# XXX coco metrics not included for simplicity
def run(model, loader, mode='train'):
Y
Yang Zhang 已提交
467
    total_loss = 0.
Y
Yang Zhang 已提交
468 469 470
    total_time = 0.
    device_ids = list(range(FLAGS.num_devices))
    start = time.time()
Y
Yang Zhang 已提交
471

Y
Yang Zhang 已提交
472 473 474 475 476
    for idx, batch in enumerate(loader()):
        outputs, losses = getattr(model, mode)(
            batch[0], batch[1], device='gpu', device_ids=device_ids)

        total_loss += np.sum(losses)
Y
Yang Zhang 已提交
477
        if idx > 1:  # skip first two steps
Y
Yang Zhang 已提交
478 479
            total_time += time.time() - start
        if idx % 10 == 0:
D
dengkaipeng 已提交
480
            logger.info("{:04d}: loss {:0.3f} time: {:0.3f}".format(
Y
Yang Zhang 已提交
481
                idx, total_loss / (idx + 1), total_time / max(1, (idx - 1))))
Y
Yang Zhang 已提交
482 483 484 485 486 487 488 489 490 491
        start = time.time()


def main():
    @contextlib.contextmanager
    def null_guard():
        yield

    epoch = FLAGS.epoch
    batch_size = FLAGS.batch_size
Y
Yang Zhang 已提交
492
    guard = fluid.dygraph.guard() if FLAGS.dynamic else null_guard()
Y
Yang Zhang 已提交
493 494

    train_loader = fluid.io.xmap_readers(
Y
Yang Zhang 已提交
495
        batch_transform,
Y
Yang Zhang 已提交
496 497
        paddle.batch(
            fluid.io.xmap_readers(
Y
Yang Zhang 已提交
498
                sample_transform,
Y
Yang Zhang 已提交
499 500 501 502 503 504 505
                coco2017(FLAGS.data, 'train'),
                process_num=8,
                buffer_size=4 * batch_size),
            batch_size=batch_size,
            drop_last=True),
        process_num=2, buffer_size=4)

Y
Yang Zhang 已提交
506 507 508
    val_sample_transform = partial(sample_transform, mode='val')
    val_batch_transform = partial(batch_transform, mode='val')

Y
Yang Zhang 已提交
509
    val_loader = fluid.io.xmap_readers(
Y
Yang Zhang 已提交
510
        val_batch_transform,
Y
Yang Zhang 已提交
511 512
        paddle.batch(
            fluid.io.xmap_readers(
Y
Yang Zhang 已提交
513
                val_sample_transform,
Y
Yang Zhang 已提交
514 515 516
                coco2017(FLAGS.data, 'val'),
                process_num=8,
                buffer_size=4 * batch_size),
D
dengkaipeng 已提交
517
            batch_size=1),
Y
Yang Zhang 已提交
518 519 520 521 522 523
        process_num=2, buffer_size=4)

    if not os.path.exists('yolo_checkpoints'):
        os.mkdir('yolo_checkpoints')

    with guard:
D
dengkaipeng 已提交
524 525
        NUM_CLASSES=7
        model = YOLOv3(num_classes=NUM_CLASSES)
Y
Yang Zhang 已提交
526
        # XXX transfer learning
D
dengkaipeng 已提交
527 528
        if FLAGS.pretrain_weights is not None:
            model.backbone.load(FLAGS.pretrain_weights)
Y
Yang Zhang 已提交
529
        if FLAGS.weights is not None:
D
dengkaipeng 已提交
530
            model.load(FLAGS.weights)
Y
Yang Zhang 已提交
531
        optim = make_optimizer(parameter_list=model.parameters())
D
dengkaipeng 已提交
532 533 534
        anno_path = os.path.join(FLAGS.data, 'annotations', 'instances_val2017.json')
        model.prepare(optim,
                      YoloLoss(num_classes=NUM_CLASSES),
535 536 537 538
                      # For YOLOv3, output variable in train/eval is different,
                      # which is not supported by metric, add by callback later?
                      # metrics=COCOMetric(anno_path, with_background=False)
                      )
Y
Yang Zhang 已提交
539 540

        for e in range(epoch):
541 542 543
            logger.info("======== train epoch {} ========".format(e))
            run(model, train_loader)
            model.save('yolo_checkpoints/{:02d}'.format(e))
D
dengkaipeng 已提交
544
            logger.info("======== eval epoch {} ========".format(e))
Y
Yang Zhang 已提交
545
            run(model, val_loader, mode='eval')
D
dengkaipeng 已提交
546 547 548
            # should be called in fit()
            for metric in model._metrics:
                metric.accumulate()
D
dengkaipeng 已提交
549
                metric.reset()
Y
Yang Zhang 已提交
550 551 552 553 554


if __name__ == '__main__':
    parser = argparse.ArgumentParser("Yolov3 Training on COCO")
    parser.add_argument('data', metavar='DIR', help='path to COCO dataset')
Y
Yang Zhang 已提交
555 556
    parser.add_argument(
        "-d", "--dynamic", action='store_true', help="enable dygraph mode")
Y
Yang Zhang 已提交
557 558 559
    parser.add_argument(
        "-e", "--epoch", default=300, type=int, help="number of epoch")
    parser.add_argument(
Y
Yang Zhang 已提交
560 561
        '--lr', '--learning-rate', default=0.001, type=float, metavar='LR',
        help='initial learning rate')
Y
Yang Zhang 已提交
562
    parser.add_argument(
Y
Yang Zhang 已提交
563
        "-b", "--batch_size", default=64, type=int, help="batch size")
Y
Yang Zhang 已提交
564
    parser.add_argument(
Y
Yang Zhang 已提交
565
        "-n", "--num_devices", default=8, type=int, help="number of devices")
Y
Yang Zhang 已提交
566
    parser.add_argument(
D
dengkaipeng 已提交
567
        "-p", "--pretrain_weights", default=None, type=str,
Y
Yang Zhang 已提交
568
        help="path to pretrained weights")
D
dengkaipeng 已提交
569 570 571
    parser.add_argument(
        "-w", "--weights", default=None, type=str,
        help="path to model weights")
Y
Yang Zhang 已提交
572
    FLAGS = parser.parse_args()
Y
Yang Zhang 已提交
573
    assert FLAGS.data, "error: must provide data path"
Y
Yang Zhang 已提交
574
    main()