如果本文帮助到了你,欢迎[点赞、收藏、关注]哦~

【知识】设置python/cuda/numpy的随机数种子_python

import torch
import random
import numpy as np

def set_random_seed(seed):
    # 设置Python的随机种子
    random.seed(seed)
    # 设置NumPy的随机种子
    np.random.seed(seed)
    # 设置CPU的随机种子
    torch.manual_seed(seed)
    # 设置当前GPU设备的随机种子
    torch.cuda.manual_seed(seed)
    # 设置所有GPU设备的随机种子(如果使用多GPU)
    torch.cuda.manual_seed_all(seed)
    # 禁用CuDNN中可能导致非确定性行为的选项
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

# 设置随机种子
seed = 42
set_random_seed(seed)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.