当前位置:   article > 正文

YOLOv5代码解析——train.py

YOLOv5代码解析——train.py

         train.py是训练YOLOV5使用的代码,后边根据函数调用展开。首先是主函数,显示有parse_opt()函数获得参数,然后把参数传给main函数。

  1. if __name__ == '__main__':
  2. opt = parse_opt() # 获得参数
  3. main(opt) # 把参数传给main函数完成后续操作

1、parse_opt()函数主要用来加载参数,都有默认值,在使用的时候重新进行配置。

  1. def parse_opt(known=False):
  2. parser = argparse.ArgumentParser()
  3. # 加载预训练权重
  4. parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path')
  5. # 加载cfg配置文件(网络结构)
  6. parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
  7. # 加载数据集
  8. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
  9. # 配置超参数
  10. parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
  11. # epochs 训练轮次
  12. parser.add_argument('--epochs', type=int, default=100, help='total training epochs')
  13. # batch-size 训练批次,默认16
  14. parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
  15. # 设置图片大小
  16. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
  17. # 是否采用矩形训练,默认False
  18. parser.add_argument('--rect', action='store_true', help='rectangular training')
  19. # 是否接着上次的训练结构继续训练
  20. parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
  21. # 不保存训练结果
  22. parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
  23. # noval 最后进行测试, 设置了之后就是训练结束都测试一下, 不设置每轮都计算mAP, 建议不设置#
  24. parser.add_argument('--noval', action='store_true', help='only validate final epoch')
  25. # 不自动调整anchor,默认为false(yolov5会根据数据集自动计算anchor,这是特色之一)
  26. parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
  27. parser.add_argument('--noplots', action='store_true', help='save no plot files')
  28. # 遗传算法调参
  29. parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
  30. # 谷歌优盘(一般用不到)
  31. parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
  32. # cache 是否提前缓存图片到内存,以加快训练速度,默认False
  33. parser.add_argument('--cache', type=str, nargs='?', const='ram', help='image --cache ram/disk')
  34. # mage-weights 使用图片采样策略,默认不使用
  35. parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
  36. # gpu设备选择,
  37. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  38. # 多尺度训练
  39. parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
  40. # single-cls 数据集是否多类/默认True
  41. parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
  42. # # optimizer 优化器选择 / 提供了三种优化器
  43. parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
  44. # sync-bn:是否使用跨卡同步BN,在DDP模式使用
  45. parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
  46. # 使用的线程数量(谨慎选择,适度的workers有助于提升训练速度,workers过大反而会导致变慢)
  47. parser.add_argument('--workers', type=int, default=12, help='max dataloader workers (per RANK in DDP mode)')
  48. # 保存路径 / 默认保存路径 ./runs/ train
  49. parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name')
  50. # 实验名称
  51. parser.add_argument('--name', default='exp', help='save to project/name')
  52. # 项目位置是否存在 / 默认是都不存在
  53. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  54. parser.add_argument('--quad', action='store_true', help='quad dataloader')
  55. # 余弦学习率
  56. parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
  57. # 标签平滑,默认不使用
  58. parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
  59. # 100次不更新就停止训练
  60. parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
  61. # --freeze冻结训练 可以设置 default = [0] 数据量大的情况下,建议不设置这个参数
  62. parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
  63. # 多少个epoch保存一下checkpoint
  64. parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
  65. # 随机数种子
  66. parser.add_argument('--seed', type=int, default=0, help='Global training seed')
  67. # --local_rank 进程编号 / 多卡使用
  68. parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
  69. # Logger arguments
  70. # # Weights & Biases arguments,类似于tensorboard的可视化工具
  71. parser.add_argument('--entity', default=None, help='Entity')
  72. parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='Upload data, "val" option')
  73. parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval')
  74. parser.add_argument('--artifact_alias', type=str, default='latest', help='Version of dataset artifact to use')
  75. return parser.parse_known_args()[0] if known else parser.parse_args()

2、main函数这里没有介绍遗传净化算法,后边会更新博客单独介绍这一部分。

2.1 打印参数,检查环境
  1. # Checks
  2. if RANK in {-1, 0}:
  3. # 输出所有训练参数
  4. print_args(vars(opt))
  5. # 检查代码版本是否更新
  6. check_git_status()
  7. # 检查所需要的包是否都安装了
  8. check_requirements(ROOT / 'requirements.txt')
2.2 断点训练,判断是否要接着上一次的训练继续训练,如果是,就把参数替换为上一次的参数,如果不使用断点训练,直接加载参数并保存到一个文件中。
  1. # Resume (from specified or most recent last.pt) 断点训练
  2. if opt.resume and not check_comet_resume(opt) and not opt.evolve:
  3. # isinstance()是否是已经知道的类型
  4. # 如果resume是True,则通过get_lastest_run()函数找到runs为文件夹中最近的权重文件last.pt
  5. last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
  6. opt_yaml = last.parent.parent / 'opt.yaml' # train options yaml
  7. opt_data = opt.data # original dataset
  8. # 把opt的参数替换为last.pt中opt的参数
  9. if opt_yaml.is_file():
  10. with open(opt_yaml, errors='ignore') as f:
  11. d = yaml.safe_load(f)
  12. else:
  13. d = torch.load(last, map_location='cpu')['opt']
  14. opt = argparse.Namespace(**d) # replace
  15. opt.cfg, opt.weights, opt.resume = '', str(last), True # reinstate
  16. if is_url(opt_data):
  17. opt.data = check_file(opt_data) # avoid HUB resume auth timeout
  18. # 不使用断点训练
  19. else:
  20. # 加载参数
  21. opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \
  22. check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks
  23. assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
  24. if opt.evolve:
  25. if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve
  26. opt.project = str(ROOT / 'runs/evolve')
  27. opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
  28. if opt.name == 'cfg':
  29. opt.name = Path(opt.cfg).stem # use model.yaml as name
  30. # 保存相关信息到文件中
  31. opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))

2.3 分布式训练

  1. # DDP mode
  2. # 选择device
  3. device = select_device(opt.device, batch_size=opt.batch_size)
  4. if LOCAL_RANK != -1:
  5. msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
  6. assert not opt.image_weights, f'--image-weights {msg}'
  7. assert not opt.evolve, f'--evolve {msg}'
  8. assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size'
  9. assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
  10. assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
  11. # 根据编号选择设备
  12. #使用torch.cuda.set_device()可以更方便地将模型和数据加载到对应GPU上, 直接定义模型之前加入一行代码即可
  13. # torch.cuda.set_device(gpu_id) #单卡
  14. # torch.cuda.set_device('cuda:'+str(gpu_ids))
  15. #可指定多卡
  16. torch.cuda.set_device(LOCAL_RANK)
  17. device = torch.device('cuda', LOCAL_RANK)
  18. # 初始化多进程
  19. dist.init_process_group(backend='nccl' if dist.is_nccl_available() else 'gloo',
  20. timeout=timedelta(seconds=10800))

3、train函数

3.1 train函数——基本配置信息

解析了从opt传入的参数,创建了训练结果的保存路径,对绘图的参数进行了配置。

  1. ##################### 基本信息配置 ##################################
  2. # 解析opt传入的参数
  3. save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \
  4. Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \
  5. opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze
  6. callbacks.run('on_pretrain_routine_start')
  7. # Directories
  8. w = save_dir / 'weights' # weights dir
  9. # 创建保存训练结果的文件夹
  10. (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
  11. # 保存训练结果的目录 ,如runs/train/exp1/weights/last.pt
  12. last, best = w / 'last.pt', w / 'best.pt'
  13. # Hyperparameters
  14. if isinstance(hyp, str):
  15. with open(hyp, errors='ignore') as f:
  16. hyp = yaml.safe_load(f) # load hyps dict
  17. # 打印超参数,彩色字体
  18. LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
  19. opt.hyp = hyp.copy() # for saving hyps to checkpoints
  20. # Save run settings
  21. if not evolve:
  22. yaml_save(save_dir / 'hyp.yaml', hyp)
  23. yaml_save(save_dir / 'opt.yaml', vars(opt))
  24. # Loggers
  25. data_dict = None
  26. if RANK in {-1, 0}:
  27. loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
  28. # Register actions
  29. for k in methods(loggers):
  30. callbacks.register_action(k, callback=getattr(loggers, k))
  31. # Process custom dataset artifact link
  32. data_dict = loggers.remote_dataset
  33. if resume: # If resuming runs from remote artifact
  34. weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
  35. # Config
  36. plots = not evolve and not opt.noplots # create plots
  37. cuda = device.type != 'cpu'
  38. # 随机种子
  39. init_seeds(opt.seed + 1 + RANK, deterministic=True)
  40. # 存在子进程-分布式训练
  41. with torch_distributed_zero_first(LOCAL_RANK):
  42. data_dict = data_dict or check_dataset(data) # check if None
  43. # 获取训练集和验证集的路径
  44. train_path, val_path = data_dict['train'], data_dict['val']
  45. # 设置类别,判断是否为蛋类
  46. nc = 1 if single_cls else int(data_dict['nc']) # number of classes
  47. # 类别对应的名称
  48. names = {0: 'item'} if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
  49. # 判断是否是coco数据集
  50. is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset
3.2 train函数——模型加载/断点训练
  1. # Model
  2. # 检查文件后缀是否是.pt
  3. check_suffix(weights, '.pt') # check weights
  4. pretrained = weights.endswith('.pt')
  5. if pretrained:
  6. # torch_distributed_zero_first(RANK): 用于同步不同进程对数据读取的上下文管理器
  7. with torch_distributed_zero_first(LOCAL_RANK):
  8. # 如果不存在就从网站上下载
  9. weights = attempt_download(weights) # download if not found locally
  10. # 加载预训练模型及参数
  11. ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak
  12. """
  13. 两种加载模型的方式: opt.cfg / ckpt['model'].yaml
  14. 使用resume-断点训练: 选择ckpt['model']yaml创建模型, 且不加载anchor
  15. 使用断点训练时,保存的模型会保存anchor,所以不需要加载
  16. """
  17. model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
  18. exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
  19. # 筛选字典中断电键值对,把exclude删除
  20. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  21. csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
  22. model.load_state_dict(csd, strict=False) # load
  23. LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
  24. else:
  25. # 不使用预训练权重
  26. model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
  27. amp = check_amp(model) # check AMP
3.3 train函数——冻结训练层
  1. # Freeze 冻结网络的训练层
  2. freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
  3. for k, v in model.named_parameters():
  4. v.requires_grad = True # train all layers
  5. # v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results)
  6. if any(x in k for x in freeze):
  7. LOGGER.info(f'freezing {k}')
  8. # 冻结的训练层梯度不更新
  9. v.requires_grad = False
3.4 train函数——图片大小和batchsize设置
  1. # Image size
  2. gs = max(int(model.stride.max()), 32) # grid size (max stride)
  3. # 检查图片大小
  4. imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
  5. # Batch size
  6. if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
  7. batch_size = check_train_batch_size(model, imgsz, amp)
  8. loggers.on_params_update({'batch_size': batch_size})
3.5 train函数——优化器设置
  1. """
  2. yolov5这里并不是根据batch size的大小去更新梯度,而是设置了一个固定的值
  3. nbs = 64
  4. batchsize = 16
  5. accumulate = 64/16=4
  6. 梯度累计accumlate次之后更新一次模型,相当于使用更大的batch_size
  7. """
  8. # Optimizer
  9. nbs = 64 # nominal batch size
  10. accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
  11. # 权重衰减参数
  12. hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
  13. optimizer = smart_optimizer(model, opt.optimizer, hyp['lr0'], hyp['momentum'], hyp['weight_decay'])
3.6 train函数—— 学习率/EMA/显卡设置
  1. # Scheduler
  2. # 是否使用余弦学习率调整方式
  3. if opt.cos_lr:
  4. lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
  5. else:
  6. lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
  7. scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
  8. # EMA 对模型的参数做平均,给予近期数据更高权重的平均方法
  9. ema = ModelEMA(model) if RANK in {-1, 0} else None
  10. # Resume
  11. best_fitness, start_epoch = 0.0, 0
  12. if pretrained:
  13. if resume:
  14. best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
  15. del ckpt, csd
  16. # DP mode 单机多卡
  17. if cuda and RANK == -1 and torch.cuda.device_count() > 1:
  18. LOGGER.warning(
  19. 'WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n'
  20. 'See Multi-GPU Tutorial at https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training to get started.'
  21. )
  22. model = torch.nn.DataParallel(model)
  23. # SyncBatchNorm 多卡归一化
  24. if opt.sync_bn and cuda and RANK != -1:
  25. model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
  26. LOGGER.info('Using SyncBatchNorm()')
3.7 train函数——数据加载/anchor 调整
  1. # Trainloader 训练集数据加载
  2. train_loader, dataset = create_dataloader(train_path,
  3. imgsz,
  4. batch_size // WORLD_SIZE,
  5. gs,
  6. single_cls,
  7. hyp=hyp,
  8. augment=True,
  9. cache=None if opt.cache == 'val' else opt.cache,
  10. rect=opt.rect,
  11. rank=LOCAL_RANK,
  12. workers=workers,
  13. image_weights=opt.image_weights,
  14. quad=opt.quad,
  15. prefix=colorstr('train: '),
  16. shuffle=True,
  17. seed=opt.seed)
  18. # mlc 标签编号最大值
  19. labels = np.concatenate(dataset.labels, 0)
  20. mlc = int(labels[:, 0].max()) # max label class
  21. # 判断编号是否正确
  22. assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
  23. # Process 0
  24. # 验证集数据加载
  25. if RANK in {-1, 0}:
  26. val_loader = create_dataloader(val_path,
  27. imgsz,
  28. batch_size // WORLD_SIZE * 2,
  29. gs,
  30. single_cls,
  31. hyp=hyp,
  32. cache=None if noval else opt.cache,
  33. rect=True,
  34. rank=-1,
  35. workers=workers * 2,
  36. pad=0.5,
  37. prefix=colorstr('val: '))[0]
  38. if not resume: # 不使用断点训练
  39. if not opt.noautoanchor:
  40. # dataset是在上边创建train_loader时生成的
  41. # hyp['anchor_t']是从配置文件hpy.scratch.yaml读取的超参数 anchor_t:4.0
  42. # 当配置文件中的anchor计算bpr(best possible recall)小于0.98时才会重新计算anchor
  43. # best possible recall最大值1,如果bpr小于0.98,程序会根据数据集的label自动学习anchor的尺寸
  44. check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) # run AutoAnchor
  45. # 半精度
  46. model.half().float() # pre-reduce anchor precision
  47. callbacks.run('on_pretrain_routine_end', labels, names)
3.8 train函数——训练配置
  1. ############# 训练配置 ##############
  2. # DDP mode 多机多卡
  3. if cuda and RANK != -1:
  4. model = smart_DDP(model)
  5. # Model attributes
  6. # smart_DDP和de_parallel代码在utils.torch_utils中
  7. # 对hpy字典中的一些值进行缩放和预设置,以适应不同的层级、类别、图像尺寸和标签平滑需求
  8. # 默认 nl = 3
  9. nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
  10. # hyp-low中给出的 box=0.05; cls=0.5; obj=1.0
  11. # hyp['box'] = 0.05*3/3=0.05
  12. hyp['box'] *= 3 / nl # scale to layers
  13. # hyp['cls'] = 0.5*20/80*3/3=0.125
  14. hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers
  15. # hyp['obj']=1.0*(640/640)**2*3/nl=1
  16. hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
  17. hyp['label_smoothing'] = opt.label_smoothing
  18. model.nc = nc # attach number of classes to model
  19. model.hyp = hyp # attach hyperparameters to model
  20. # 从训练样本标签得到类别权重(和类别中的目标数即类别频率成反比)
  21. model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
  22. model.names = names
3.9 train函数——训练

        开始训练的代码,使用先前生成的trian_loader读取图片,送入模型开始训练,并计算损失进行反向传播,以及每轮训练后进行验证计算P,R,mAP等。

  1. ########################## Start training ##########################
  2. t0 = time.time()
  3. nb = len(train_loader) # number of batches
  4. nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
  5. # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
  6. last_opt_step = -1
  7. # 初始化maps(每个类别的map)和results
  8. maps = np.zeros(nc) # mAP per class
  9. results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
  10. # 设置学习率衰减所进行到的轮次,即使打断训练,使用resume接着训练也能正常衔接之前的训练进行学习率衰减
  11. scheduler.last_epoch = start_epoch - 1 # do not move
  12. # 设置amp混合精度训练
  13. scaler = torch.cuda.amp.GradScaler(enabled=amp)
  14. # 早停止
  15. stopper, stop = EarlyStopping(patience=opt.patience), False
  16. # 初始化损失
  17. compute_loss = ComputeLoss(model) # init loss class
  18. callbacks.run('on_train_start')
  19. LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
  20. f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
  21. f"Logging results to {colorstr('bold', save_dir)}\n"
  22. f'Starting training for {epochs} epochs...')
  23. # 正式开始训练
  24. for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
  25. callbacks.run('on_train_epoch_start')
  26. model.train()
  27. # Update image weights (optional, single-GPU only)
  28. if opt.image_weights:
  29. """
  30. 如果设置图片采样策略
  31. 则根据前面初始化的图片采样权重model.class_weights以及maps配合每张图片包含的类别数
  32. 通过random.choices生成图片所有indices从而进行采样
  33. """
  34. cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
  35. iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
  36. dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
  37. # Update mosaic border (optional)
  38. # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
  39. # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
  40. mloss = torch.zeros(3, device=device) # mean losses
  41. if RANK != -1:
  42. train_loader.sampler.set_epoch(epoch)
  43. pbar = enumerate(train_loader)
  44. LOGGER.info(('\n' + '%11s' * 7) % ('Epoch', 'GPU_mem', 'box_loss', 'obj_loss', 'cls_loss', 'Instances', 'Size'))
  45. if RANK in {-1, 0}:
  46. # 进度条显示
  47. pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
  48. optimizer.zero_grad() # 梯度清零
  49. for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
  50. callbacks.run('on_train_batch_start')
  51. ni = i + nb * epoch # number integrated batches (since train start)
  52. imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
  53. """
  54. 热身训练(前nw次迭代,一般是3)
  55. 在前nw次迭代中,根据以下方式选取accumulate和学习率
  56. """
  57. # Warmup
  58. if ni <= nw:
  59. xi = [0, nw] # x interp
  60. # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
  61. accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
  62. for j, x in enumerate(optimizer.param_groups):
  63. """
  64. bias的学习率从0.1下降到基准学习率lr*lf(epoch),
  65. 其他的参数学习率从0增加到lr*lf(epoch).
  66. lf为上面设置的余弦退火的衰减函数
  67. 动量momentum也从0.9慢慢变到hyp['momentum'](default=0.937)
  68. """
  69. # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
  70. x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 0 else 0.0, x['initial_lr'] * lf(epoch)])
  71. if 'momentum' in x:
  72. x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
  73. # Multi-scale
  74. if opt.multi_scale:
  75. """
  76. Multi-scale 设置多尺度训练,从imgsz * 0.5, imgsz * 1.5 + gs随机选取尺寸
  77. """
  78. sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5) + gs) // gs * gs # size
  79. sf = sz / max(imgs.shape[2:]) # scale factor
  80. if sf != 1:
  81. ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
  82. imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
  83. # Forward
  84. with torch.cuda.amp.autocast(amp):
  85. pred = model(imgs) # forward
  86. # loss是总损失 loss_items是一个元组,包含分类损失,obj损失,boundingbox的回归损失和总损失
  87. loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
  88. if RANK != -1:
  89. # 平均不同gpu之间的梯度
  90. loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
  91. if opt.quad:
  92. loss *= 4.
  93. # Backward
  94. scaler.scale(loss).backward()
  95. # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
  96. # 模型反向传播accumulate次之后再根据累计的梯度更新一次参数
  97. if ni - last_opt_step >= accumulate:
  98. scaler.unscale_(optimizer) # unscale gradients
  99. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
  100. scaler.step(optimizer) # optimizer.step
  101. scaler.update()
  102. optimizer.zero_grad()
  103. if ema:
  104. ema.update(model)
  105. last_opt_step = ni
  106. # Log
  107. if RANK in {-1, 0}:
  108. mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
  109. mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
  110. pbar.set_description(('%11s' * 2 + '%11.4g' * 5) %
  111. (f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
  112. callbacks.run('on_train_batch_end', model, ni, imgs, targets, paths, list(mloss))
  113. if callbacks.stop_training:
  114. return
  115. # end batch ------------------------------------------------------------------------------------------------
  116. # Scheduler 学习率衰减
  117. lr = [x['lr'] for x in optimizer.param_groups] # for loggers
  118. scheduler.step()
  119. if RANK in {-1, 0}:
  120. # mAP
  121. callbacks.run('on_train_epoch_end', epoch=epoch)
  122. # 把model中的属性赋值给ema
  123. ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
  124. # 判断是否是最后一轮
  125. final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
  126. # notest: 是否只测试最后一轮 True: 只测试最后一轮 False: 每轮训练完都测试mAP
  127. if not noval or final_epoch: # Calculate mAP
  128. # 测试使用的是ema(对模型的参数做平均)模型
  129. # verbose设置为true后,每轮的验证都输出每个类别的信息
  130. results, maps, _ = validate.run(data_dict,
  131. batch_size=batch_size // WORLD_SIZE * 2,
  132. imgsz=imgsz,
  133. half=amp,
  134. model=ema.ema,
  135. single_cls=single_cls,
  136. dataloader=val_loader,
  137. save_dir=save_dir,
  138. plots=False,
  139. callbacks=callbacks,
  140. compute_loss=compute_loss,
  141. verbose=True)
  142. # Update best mAP
  143. fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
  144. stop = stopper(epoch=epoch, fitness=fi) # early stop check
  145. if fi > best_fitness:
  146. best_fitness = fi
  147. log_vals = list(mloss) + list(results) + lr
  148. callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
  149. # Save model
  150. """
  151. 保存带checkpoint的模型用于inference或resuming training
  152. 保存模型的同时还保存epoch,results,optimizer等信息
  153. optimizer在最后一轮不会报错
  154. model保存的是EMA后的模型
  155. """
  156. if (not nosave) or (final_epoch and not evolve): # if save
  157. ckpt = {
  158. 'epoch': epoch,
  159. 'best_fitness': best_fitness,
  160. 'model': deepcopy(de_parallel(model)).half(),
  161. 'ema': deepcopy(ema.ema).half(),
  162. 'updates': ema.updates,
  163. 'optimizer': optimizer.state_dict(),
  164. 'opt': vars(opt),
  165. 'git': GIT_INFO, # {remote, branch, commit} if a git repo
  166. 'date': datetime.now().isoformat()}
  167. # Save last, best and delete
  168. torch.save(ckpt, last)
  169. if best_fitness == fi:
  170. torch.save(ckpt, best)
  171. if opt.save_period > 0 and epoch % opt.save_period == 0:
  172. torch.save(ckpt, w / f'epoch{epoch}.pt')
  173. del ckpt
  174. callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
  175. # EarlyStopping
  176. if RANK != -1: # if DDP training
  177. broadcast_list = [stop if RANK == 0 else None]
  178. dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
  179. if RANK != 0:
  180. stop = broadcast_list[0]
  181. if stop:
  182. break # must break all DDP ranks
  183. # end epoch ----------------------------------------------------------------------------------------------------
  184. # end training --------------------------

3.10 train函数——打印训练信息

  1. ############################ 打印训练信息 #########################
  2. if RANK in {-1, 0}:
  3. LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
  4. for f in last, best:
  5. if f.exists():
  6. strip_optimizer(f) # strip optimizers
  7. if f is best:
  8. LOGGER.info(f'\nValidating {f}...')
  9. results, _, _ = validate.run(
  10. data_dict,
  11. batch_size=batch_size // WORLD_SIZE * 2,
  12. imgsz=imgsz,
  13. model=attempt_load(f, device).half(),
  14. iou_thres=0.65 if is_coco else 0.60, # best pycocotools at iou 0.65
  15. single_cls=single_cls,
  16. dataloader=val_loader,
  17. save_dir=save_dir,
  18. save_json=is_coco,
  19. verbose=True,
  20. plots=plots,
  21. callbacks=callbacks,
  22. compute_loss=compute_loss) # val best model with plots
  23. if is_coco:
  24. callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
  25. callbacks.run('on_train_end', last, best, epoch, results)
  26. torch.cuda.empty_cache() # 释放显存
  27. return results

4、代码使用

        使用的命令如下,主要指定数据 --data 、权重 --weights 和模型配置文件 --cfg,其他参数选择使用。为了方便建议写入到xxx.sh文件进行运行,如果权限不够无法使用./xxx.sh运行,使用chmod +777 xxx.sh修改权限,就可以运行了。

 python train.py --data ./data/mydata.yaml --weight ./weights/yolov5l.pt --cfg ./models/yolov5l.yaml 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/167675
推荐阅读
相关标签
  

闽ICP备14008679号