生成随机种子来播种 Pytorch 的最佳实践?

Cha*_*ker 4 pytorch

我真正想要的是播种数据集和数据加载器。我正在改编代码:

https://gist.github.com/kevinzakka/d33bf8d6c7f06a9d8c76d97a7879f5cb

有人知道如何正确播种吗?在 Pytorch 中播种的最佳实践是什么?

老实说,我不知道 GPU 与 CPU 是否有特定的算法方式。我最关心一般的 pytorch 并确保我的代码是“真正随机的”。特别是当它使用 GPU 我猜......


有关的:


我的回答被删除了,内容如下:

我不知道这是否对 pytorch 来说是最好的,但这似乎是对任何编程语言来说最好的:


通常,您可以用任何编程语言获得的最佳随机样本是通过操作系统生成的。在Python中,您可以使用os模块:

random_data = os.urandom(4)

通过这种方式,您可以获得加密安全的随机字节序列,您可以将其转换为数字数据类型以用作种子。

seed = int.from_bytes(random_data, byteorder="big")

编辑:代码片段仅适用于 Python 3


''' 大于 4 我收到此错误:

ValueError:种子必须介于 0 和 2**32 - 1 ''' 之间

兰德_大小 = 4

coo*_*ter 7

看看https://pytorch.org/docs/stable/notes/randomness.html

这就是我用的

def seed_everything(seed=42):
  random.seed(seed)
  os.environ['PYTHONHASHSEED'] = str(seed)
  np.random.seed(seed)
  torch.manual_seed(seed)
  torch.backends.cudnn.deterministic = True
  torch.backends.cudnn.benchmark = False
Run Code Online (Sandbox Code Playgroud)

最后两个参数 (cudnn) 用于 GPU

您可以按如下方式生成种子:

def get_truly_random_seed_through_os():
    """
    Usually the best random sample you could get in any programming language is generated through the operating system. 
    In Python, you can use the os module.

    source: /sf/ask/4019184781/#57416967
    """
    RAND_SIZE = 4
    random_data = os.urandom(
        RAND_SIZE
    )  # Return a string of size random bytes suitable for cryptographic use.
    random_seed = int.from_bytes(random_data, byteorder="big")
    return random_seed
Run Code Online (Sandbox Code Playgroud)