在训练和测试的时候可以在脚本中加入如下代码,对结果进行固定,确保每次运行脚本结果保持一致:

1
2
3
4
5
6
7
def seed_torch(seed):
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
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
def seed_torch(seed):
"""
Set the random seed for various modules to ensure reproducibility.

Args:
seed (int): The seed value to be set.
"""
# Set PYTHONHASHSEED environment variable
os.environ['PYTHONHASHSEED'] = str(seed)

# Set random seed for Python's built-in random module
random.seed(seed)

# Set random seed for numpy
np.random.seed(seed)

# Set random seed for PyTorch
torch.manual_seed(seed)

# Set random seed for PyTorch (CUDA)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.

# Ensure that the cuDNN library's benchmark mode is disabled, and that
# cuDNN is deterministic.
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True

本站由 @anonymity 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。