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
| """ YOLOv11增量训练完整脚本 功能:基于已有权重继续训练,集成增强数据与早停机制 """
import os import torch from ultralytics import YOLO from ultralytics.utils.torch_utils import de_parallel from pathlib import Path
class RetrainConfig: pretrained_weights = r"path\to\pt.pt" output_dir = r'path\to\output' data_yaml = r"path\to\dataset.yaml" img_size = 640 batch_size = 4 epochs = 300 initial_lr = 0.001 optimizer_type = 'AdamW' weight_decay = 0.0005 augment = True mosaic_prob = 0.5 mixup_prob = 0.2 amp = True, patience = 5 min_delta = 0.001 device = 'cuda' if torch.cuda.is_available() else 'cpu'
def main(cfg): os.makedirs(cfg.output_dir, exist_ok=True) model = YOLO(cfg.pretrained_weights) model.augment = { 'mosaic': cfg.mosaic_prob, 'mixup': cfg.mixup_prob, 'degrees': 45.0, 'translate': 0.2, 'shear': 0.3 } train_args = { 'data': cfg.data_yaml, 'epochs': cfg.epochs, 'batch': cfg.batch_size, 'imgsz': cfg.img_size, 'resume': False, 'patience': cfg.patience, 'augment': cfg.augment, 'lr0': cfg.initial_lr, 'optimizer': cfg.optimizer_type, 'weight_decay': cfg.weight_decay, 'project': cfg.output_dir, 'device': cfg.device, 'amp':cfg.amp, 'exist_ok': True } results = model.train(**train_args)
print(f'✅ 训练完成!最佳权重已保存至: {cfg.output_dir}')
if __name__ == '__main__': config = RetrainConfig() main(config)
|