Esempio n. 1
0
    def generate(self):
        model_path = os.path.expanduser(self.model_path)
        assert model_path.endswith(
            '.h5'), 'Keras model or weights must be a .h5 file.'

        self.yolo_model = yolo_body(
            [self.input_shape[0], self.input_shape[1], 3], self.anchors_mask,
            self.num_classes, self.phi)
        self.yolo_model.load_weights(self.model_path)
        print('{} model, anchors, and classes loaded.'.format(model_path))
        #---------------------------------------------------------#
        #   在yolo_eval函数中,我们会对预测结果进行后处理
        #   后处理的内容包括,解码、非极大抑制、门限筛选等
        #---------------------------------------------------------#
        boxes, scores, classes = DecodeBox(
            self.yolo_model.output,
            self.anchors,
            self.num_classes,
            self.input_image_shape,
            self.input_shape,
            anchor_mask=self.anchors_mask,
            max_boxes=self.max_boxes,
            confidence=self.confidence,
            nms_iou=self.nms_iou,
            letterbox_image=self.letterbox_image)
        return boxes, scores, classes
Esempio n. 2
0
def train_by_fit(optimizer, loss, train_data, train_steps, validation_data,
                 validation_steps):
    """
    使用fit方式训练,可以知道训练完的时间,以及更规范的添加callbacks参数
    :param optimizer: 优化器
    :param loss: 自定义的loss function
    :param train_data: 以tf.data封装好的训练集数据
    :param validation_data: 验证集数据
    :param train_steps: 迭代一个epoch的轮次
    :param validation_steps: 同上
    :return: None
    """
    cbk = [
        callbacks.ReduceLROnPlateau(verbose=1),
        callbacks.EarlyStopping(patience=10, verbose=1),
        callbacks.ModelCheckpoint('./model/yolov3_{val_loss:.04f}.h5',
                                  save_best_only=True,
                                  save_weights_only=True)
    ]

    model = yolo_body()
    model.compile(optimizer=optimizer, loss=loss)

    # initial_epoch用于恢复之前的训练
    model.fit(train_data,
              steps_per_epoch=max(1, train_steps),
              validation_data=validation_data,
              validation_steps=max(1, validation_steps),
              epochs=cfg.epochs,
              callbacks=cbk)
Esempio n. 3
0
 def generate(self):
     model_path = os.path.expanduser(self.model_path)
     assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
     
     self.model = yolo_body([None, None, 3], self.anchors_mask, self.num_classes, self.backbone, self.alpha)
     self.model.load_weights(self.model_path)
     print('{} model, anchors, and classes loaded.'.format(model_path))
     #---------------------------------------------------------#
     #   在DecodeBox函数中,我们会对预测结果进行后处理
     #   后处理的内容包括,解码、非极大抑制、门限筛选等
     #---------------------------------------------------------#
     self.input_image_shape = Input([2,],batch_size=1)
     inputs  = [*self.model.output, self.input_image_shape]
     outputs = Lambda(
         DecodeBox, 
         output_shape = (1,), 
         name = 'yolo_eval',
         arguments = {
             'anchors'           : self.anchors, 
             'num_classes'       : self.num_classes, 
             'input_shape'       : self.input_shape, 
             'anchor_mask'       : self.anchors_mask,
             'confidence'        : self.confidence, 
             'nms_iou'           : self.nms_iou, 
             'max_boxes'         : self.max_boxes, 
             'letterbox_image'   : self.letterbox_image
          }
     )(inputs)
     self.yolo_model = Model([self.model.input, self.input_image_shape], outputs)
Esempio n. 4
0
    def __init__(self, model_path):
        self.class_names = cfg.class_names
        self.anchors = cfg.anchors
        self.score = 0.5

        model = yolo_body()
        model.load_weights(model_path)
        self.model = model
Esempio n. 5
0
    #----------------------------------------------------#
    #   获取classes和anchor
    #----------------------------------------------------#
    class_names, num_classes = get_classes(classes_path)
    anchors, num_anchors     = get_anchors(anchors_path)

    #----------------------------------------------------#
    #   判断是否多GPU载入模型和预训练权重
    #----------------------------------------------------#
    if ngpus_per_node > 1:
        with strategy.scope():
            #------------------------------------------------------#
            #   创建yolo模型
            #------------------------------------------------------#
            model_body  = yolo_body((None, None, 3), anchors_mask, num_classes, backbone, alpha, weight_decay=weight_decay)
            if model_path != '':
                #------------------------------------------------------#
                #   载入预训练权重
                #------------------------------------------------------#
                print('Load weights {}.'.format(model_path))
                model_body.load_weights(model_path, by_name=True, skip_mismatch=True)
            if not eager:
                model = get_train_model(model_body, input_shape, num_classes, anchors, anchors_mask, label_smoothing, focal_loss, focal_alpha, focal_gamma)
    else:
        #------------------------------------------------------#
        #   创建yolo模型
        #------------------------------------------------------#
        model_body  = yolo_body((None, None, 3), anchors_mask, num_classes, backbone, alpha, weight_decay=weight_decay)
        if model_path != '':
            #------------------------------------------------------#
Esempio n. 6
0
    os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(str(x) for x in train_gpu)
    ngpus_per_node = len(train_gpu)
    print('Number of devices: {}'.format(ngpus_per_node))

    #----------------------------------------------------#
    #   获取classes和anchor
    #----------------------------------------------------#
    class_names, num_classes = get_classes(classes_path)
    anchors, num_anchors = get_anchors(anchors_path)

    K.clear_session()
    #------------------------------------------------------#
    #   创建yolo模型
    #------------------------------------------------------#
    model_body = yolo_body((input_shape[0], input_shape[1], 3),
                           anchors_mask,
                           num_classes,
                           phi=phi)
    if model_path != '':
        #------------------------------------------------------#
        #   载入预训练权重
        #------------------------------------------------------#
        print('Load weights {}.'.format(model_path))
        model_body.load_weights(model_path, by_name=True, skip_mismatch=True)

    if ngpus_per_node > 1:
        model = multi_gpu_model(model_body, gpus=ngpus_per_node)
        model = get_train_model(model, input_shape, num_classes, anchors,
                                anchors_mask, label_smoothing)
    else:
        model = get_train_model(model_body, input_shape, num_classes, anchors,
                                anchors_mask, label_smoothing)
Esempio n. 7
0
    #------------------------------------------------------#
    os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(str(x) for x in train_gpu)
    ngpus_per_node = len(train_gpu)
    print('Number of devices: {}'.format(ngpus_per_node))

    #----------------------------------------------------#
    #   获取classes和anchor
    #----------------------------------------------------#
    class_names, num_classes = get_classes(classes_path)
    anchors, num_anchors = get_anchors(anchors_path)

    K.clear_session()
    #------------------------------------------------------#
    #   创建yolo模型
    #------------------------------------------------------#
    model_body = yolo_body((None, None, 3), anchors_mask, num_classes)
    if model_path != '':
        #------------------------------------------------------#
        #   载入预训练权重
        #------------------------------------------------------#
        print('Load weights {}.'.format(model_path))
        model_body.load_weights(model_path, by_name=True, skip_mismatch=True)

    if ngpus_per_node > 1:
        model = multi_gpu_model(model_body, gpus=ngpus_per_node)
        model = get_train_model(model, input_shape, num_classes, anchors,
                                anchors_mask, label_smoothing, focal_loss,
                                focal_alpha, focal_gamma)
    else:
        model = get_train_model(model_body, input_shape, num_classes, anchors,
                                anchors_mask, label_smoothing, focal_loss,
Esempio n. 8
0
#--------------------------------------------#
#   该部分代码用于看网络结构
#--------------------------------------------#
from nets.yolo import yolo_body

if __name__ == "__main__":
    input_shape = [416, 416, 3]
    anchors_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
    num_classes = 80

    model = yolo_body(input_shape, anchors_mask, num_classes)
    model.summary()

    for i, layer in enumerate(model.layers):
        print(i, layer.name)
Esempio n. 9
0
#--------------------------------------------#
#   该部分代码用于看网络结构
#--------------------------------------------#
from nets.yolo import yolo_body
from utils.utils import net_flops

if __name__ == "__main__":
    input_shape     = [416, 416, 3]
    anchors_mask    = [[3, 4, 5], [1, 2, 3]]
    num_classes     = 80
    phi             = 0

    model = yolo_body([input_shape[0], input_shape[1], 3], anchors_mask, num_classes, phi=phi)
    #--------------------------------------------#
    #   查看网络结构网络结构
    #--------------------------------------------#
    model.summary()
    #--------------------------------------------#
    #   计算网络的FLOPS
    #--------------------------------------------#
    net_flops(model, table=False)
    
    #--------------------------------------------#
    #   获得网络每个层的名称与序号
    #--------------------------------------------#
    # for i,layer in enumerate(model.layers):
    #     print(i,layer.name)
Esempio n. 10
0
#--------------------------------------------#
#   该部分代码用于看网络结构
#--------------------------------------------#
from nets.yolo import yolo_body
from utils.utils import net_flops

if __name__ == "__main__":
    input_shape = [416, 416]
    anchors_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
    num_classes = 80
    backbone = 'mobilenetv1'

    model = yolo_body([input_shape[0], input_shape[1], 3],
                      anchors_mask,
                      num_classes,
                      backbone=backbone)
    #--------------------------------------------#
    #   查看网络结构网络结构
    #--------------------------------------------#
    model.summary()
    #--------------------------------------------#
    #   计算网络的FLOPS
    #--------------------------------------------#
    net_flops(model, table=False)

    #--------------------------------------------#
    #   获得网络每个层的名称与序号
    #--------------------------------------------#
    # for i,layer in enumerate(model.layers):
    #     print(i,layer.name)