当前位置:   article > 正文

YOLOv5无法稳定复现出一样结果的解决方案_yolov5每次训练结果不一样 复现

yolov5每次训练结果不一样 复现

YOLOv5无法稳定复现出一样结果的解决方案

一般情况下随机种子的设定

在训练之前呢使用这个函数定义好随机种子就可以了。

def fix_random(seed=0):
    def setup_seed(seed):
        random.seed(seed)
        np.random.seed(seed)
        torch.manual_seed(seed)
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
        torch.backends.cudnn.benchmark = False  # 针对数据的分布自动实现寻找卷积效率最高的方式(如果是true)
        torch.backends.cudnn.deterministic = True  # 实现卷积的方式是巩固定的
    setup_seed(seed)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

修改YOLOv5的随机种子设定

YOLOv5本身会有自己的随机种子。通过下列方法使用:

 python train.py --seed 2
  • 1

但是他有一个问题,YOLOv5代码中的随机种子虽然固定了,但是仍然有问题,将

utils/general.py中的init_seeds的代码进行修改:

def init_seeds(seed=0, deterministic=False):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)  
    torch.backends.cudnn.benchmark = False  
    torch.use_deterministic_algorithms(True)
    if deterministic and check_version(torch.__version__, '1.12.0'):
        torch.backends.cudnn.deterministic = True
        os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
        os.environ['PYTHONHASHSEED'] = str(seed)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

对比一下就会发现,实际上就两个参数影响到了无法稳定复现,那就是:

torch.backends.cudnn.benchmark和torch.use_deterministic_algorithms

修改好就可以解决问题了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/456947?site
推荐阅读
相关标签
  

闽ICP备14008679号