yolov5固定随机数种子
时间: 2025-02-24 20:32:17 浏览: 63
### 设置 YOLOv5 的固定随机数种子
为了确保实验结果具有可复现性,在训练和测试过程中设置固定的随机数种子是非常重要的。对于YOLOv5而言,可以通过修改`train.py`文件中的初始化部分来实现这一点。
#### 修改 `train.py`
在`train.py`中找到`init_seeds`函数调用的位置,并替换为自定义的`set_seeds`函数:
```python
from utils.general import set_logging, check_img_size
import torch
import random
import numpy as np
def set_seeds(rank=0, seed=0, deterministic=True):
# Set the seeds for all sources of randomness to ensure reproducibility.
torch.manual_seed(seed + rank)
random.seed(seed + rank)
np.random.seed(seed + rank)
if deterministic:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
```
接着,在适当位置调用此新定义的方法:
```python
if __name__ == '__main__':
parser = argparse.ArgumentParser()
...
opt = parser.parse_args()
# Initialize logging and other settings before training starts
set_logging()
device = select_device(opt.device, batch_size=opt.batch_size)
# Replace original init_seeds with custom function call here
# init_seeds(2 + rank)
set_seeds(2 + rank, seed=opt.seed, deterministic=True)[^3]
train(...)
```
通过上述更改,可以有效地控制整个程序运行过程中的各种伪随机行为,从而提高不同次执行间的稳定性与一致性[^1]。
值得注意的是,在Jupyter Notebook环境中操作时需特别小心;建议将模型预测逻辑以及随机数种子设定放在同一个Code Cell内以保证效果[^2]。
阅读全文
相关推荐


















